crootfast
Version:
大前端工程化命令行脚手架
83 lines (71 loc) • 2.37 kB
JavaScript
// 定义onFetch方法
const onFetch = {
// 通用请求方法
async request(method, url, data = null, params = {}, headers = {}) {
// 构建查询字符串
const queryString = Object.entries(params).map(([key, value]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&');
const fullUrl = queryString ? `${url}?${queryString}` : url;
// 设置请求选项
const options = {
method,
headers: {
'Content-Type': 'application/json',
...headers,
},
};
// 对POST、PUT请求附加数据
if (data) {
options.body = JSON.stringify(data);
}
// 发送请求
try {
const response = await fetch(fullUrl, options);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json(); // 假设服务器总是返回JSON格式的数据
} catch (error) {
throw error; // 抛出错误供调用者处理
}
},
// GET请求
get(url, params = {}) {
return this.request('GET', url, null, params);
},
// POST请求
post(url, data, params = {}) {
return this.request('POST', url, data, params);
},
// PUT请求
put(url, data, params = {}) {
return this.request('PUT', url, data, params);
},
// DELETE请求
delete(url, params = {}) {
return this.request('DELETE', url, null, params);
},
// 上传文件
async upload(url, data, params = {}) {
// 构建查询字符串
const queryString = Object.entries(params).map(([key, value]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&');
const fullUrl = queryString ? `${url}?${queryString}` : url;
// 使用FormData处理文件和其他表单数据
const formData = new FormData();
Object.keys(data).forEach(key => {
formData.append(key, data[key]);
});
// 发送请求
try {
const response = await fetch(fullUrl, {
method: 'POST',
body: formData, // FormData对象
// 注意:使用FormData时不需要手动设置Content-Type
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json(); // 假设服务器返回JSON格式数据
} catch (error) {
throw error; // 抛出错误供调用者处理
}
},
};
export default onFetch;