/**
*
* @param url 接口地址 eg: /test
* @param options 请求头相关的信息,实际业务当中可能某些请求需要配置额外的请求头信息
* @param timeout 接口超时时间
* @returns
*/
const request = (
url: string,
options: {
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
headers?: {
[key in string]: any;
};
body?: any;
},
timeout = 5000
) => {
const defaultOptions = {
//跨域请求,需要使用 CORS 协议。该模式下,浏览器会发送一个预检请求(Preflight Request)来检查是否允许跨域请求,
//并且会根据服务器返回的响应头来判断是否允许跨域请求
mode: 'cors',
credentials: 'omit',
};
options.headers = {
Accept: 'application/json, text/plain, */*',
Authorization: `Bearer ${window.sessionStorage.getItem('token')}`,
...options.headers,
};
if (['POST', 'GET'].includes(options.method.toUpperCase())) {
options.body = JSON.stringify(options.body);
options.headers = {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json; charset=utf-8',
...options.headers,
};
}
const Options = {
...defaultOptions,
...options,
};
return new Promise((resolve, reject) => {
// 如果使用了代理直接删除VITE_BASE_URL部分
const URL = `${import.meta.env.VITE_BASE_URL}/${url}`;
const controller = new AbortController();
const signal = controller.signal;
const timeoutPromise = (timeout: number) => {
return new Promise((resolves, rejects) => {
setTimeout(() => {
rejects(
new Response('timeout', { status: 504, statusText: 'timeout' })
);
controller.abort();
}, timeout);
});
};
Promise.race([
fetch(`${URL}`, { ...Options as any, signal: signal }),
timeoutPromise(timeout),
])
.then((res: any) => {
console.log(res, 777);
return res?.json();
})
.then((data) => {
console.log('data===', data);
resolve(data);
})
.catch((err) => {
console.log(6666, err);
reject(err);
});
});
};
export default request;
使用示例:
request('test', {
method: 'GET',
}).then((res) => {
console.log(333, res);
});