fetch 简单封装
适合写写 Demo
/**
*
* @param {string} url
* @param {RequestInit} options
*/
async function request(url, options = {}) {
const defaultOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const mergedOptions = {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...options.headers,
},
};
const response = await fetch(url, mergedOptions);
if (!response.ok) {
const error = new Error(`Request failed with status ${response.status}`);
error.response = response;
throw error;
}
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
const data = await response.json();
if (data.code !== 200) {
const error = new Error(data.message);
error.code = data.code;
error.data = data.data;
throw error;
}
return data.data;
} else {
return response.text();
}
}
该代码示例展示了一个对fetch的简单封装,包括设置默认请求方法为GET,处理Content-Type为JSON的情况,以及进行错误处理。当响应状态非200时抛出错误,并在接收到JSON数据时检查code,若不为200也抛出错误。

391

被折叠的 条评论
为什么被折叠?



