首页 > 其他分享 >学习笔记jira项目24用fetch抽象http请求

学习笔记jira项目24用fetch抽象http请求

时间:2023-02-12 22:06:15浏览次数:37  
标签:jira 24 const data fetch return http config response


const apiUrl = process.env.REACT_APP_API_URL;
interface Config extends RequestInit {
token?: string;
data?: object;
}
export const http = async (
endpoint: string,
{ data, token, headers, ...customConfig }: Config = {}
) => {
const config = {
method: "GET",
headers: {
Authorization: token ? `Bearer ${token}` : "",
"Content-Type": data ? "application/json" : "",
},
...customConfig,
};

if (config.method.toUpperCase() === "GET") {
endpoint += `?${qs.stringify(data)}`;
} else {
config.body = JSON.stringify(data || {});
}

// axios 和 fetch 的表现不一样,axios可以直接在返回状态不为2xx的时候抛出异常
return window
.fetch(`${apiUrl}/${endpoint}`, config)
.then(async (response) => {
if (response.status === 401) {
await auth.logout();
window.location.reload();
return Promise.reject({ message: "请重新登录" });
}
const data = await response.json();
if (response.ok) {
return data;
} else {
return Promise.reject(data);
}
});
};

fetch捕捉不了异常

标签:jira,24,const,data,fetch,return,http,config,response
From: https://blog.51cto.com/u_15460007/6052215

相关文章