使用 JavaScript 的 Fetch API 封装的公共请求文件示例。这个示例包含了 POST、GET、PUT 等请求方法。请注意,您需要根据您的项目需求进行相应的调整。
// request.js
const BASE_URL = 'https://api.example.com';
const handleResponse = async (response) => {
if (response.ok) {
const data = await response.json();
return data;
} else {
const error = await response.text();
throw new Error(error);
}
};
const request = async (url, options) => {
try {
const response = await fetch(`${BASE_URL}${url}`, options);
const data = await handleResponse(response);
return data;
} catch (error) {
console.error('Request failed:', error);
throw error;
}
};
export const get = (url, headers = {}) => {
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
...headers,
},
};
return request(url, options);
};
export const post = (url, body, headers = {}) => {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(body),
};
return request(url, options);
};
export const put = (url, body, headers = {}) => {
const options = {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(body),
};
return request(url, options);
};
export const del = (url, headers = {}) => {
const options = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
...headers,
},
};
return request(url, options);
};
使用这个封装好的请求文件,您可以轻松地在项目中发起 GET、POST、PUT 等请求。例如:
import * as request from './request';
// GET 请求示例
request.get('/users')
.then(data => console.log(data))
.catch(error => console.error(error));
// POST 请求示例
request.post('/users', { name: 'John Doe', age: 30 })
.then(data => console.log(data))
.catch(error => console.error(error));
// PUT 请求示例
request.put('/users/1', { name: 'Jane Doe', age: 28 })
.then(data => console.log(data))
.catch(error => console.error(error));
// DELETE 请求示例
request.del('/users/1')
.then(data => console.log(data))
.catch(error => console.error(error));
请确保您的项目支持 Fetch API,或者使用 polyfill(如:whatwg-fetch)来增加对旧浏览器的支持。