You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
1.8 KiB
45 lines
1.8 KiB
import axios from 'axios';
|
|
|
|
export default function (options) {
|
|
//配置每次发送请求都从localStorage中获取名字叫token的数据,
|
|
//添加到请求头部的Authorization属性中
|
|
const token = localStorage.getItem('token');
|
|
//Object.assign用于合并对象的数据
|
|
|
|
options.data.token = token;
|
|
// options.headers = Object.assign(
|
|
// { token: token },
|
|
// options.headers || {}
|
|
// );
|
|
|
|
//axios() 返回一个promise对象,用于异步请求
|
|
//options是一个对象,其中包含了许多用于配置请求的参数,
|
|
//例如请求的url、请求方法(GET、POST等)、请求头等
|
|
return axios(options)
|
|
.then(({ status, data, statusText }) => {
|
|
//该函数在请求成功并返回数据时被调用
|
|
//status:HTTP状态码,例如200表示请求成功。
|
|
//data:服务器返回的数据。
|
|
// statusText:HTTP状态文本,例如"OK"表示请求成功。
|
|
// console.log(data);
|
|
if (status == 200) {
|
|
return data;
|
|
} else {
|
|
throw new e(statusText);
|
|
}
|
|
})
|
|
.catch(e=>{
|
|
// 检查是否是因为token过期导致的401错误
|
|
if (e.response && e.response.status === 401) {
|
|
// 清除localStorage中的token
|
|
localStorage.removeItem('token');
|
|
// // 执行重新登录的逻辑,例如跳转到登录页面
|
|
window.location.href = '/login';
|
|
// 可以在这里返回一个特定的值或者对象,以便调用者知道需要重新登录
|
|
return { needsLogin: true };
|
|
} else {
|
|
// 其他类型的错误,直接抛出
|
|
return Promise.reject(e);
|
|
}
|
|
});
|
|
}
|