在我们的app.js文件中?export?request方法?即可
const loginPath = '/user/login';
//拦截器-请求前拦截
const authHeaderInterceptor = (url, options) => {
const o = options;
//如果不是登陆页 headers里添加 username
//headers 里面的内容是和后端协商好的
if (history.location.pathname !== loginPath) {
o.headers = {
// ...options.headers,
'St2-Api-Key': 'NjY4MjkwMGMwZWRiYmRkODViNjBi',
'username': localStorage.getItem('userToken'),
};
return {
options: o
}
}
o.headers = {
'St2-Api-Key': 'NjY4MjkwMGMwZWRiYmRkODV',
};
return {
options:o
}
}
//拦截器-响应后拦截
const demoResponseInterceptors = async (response, options) => {
const res = await response.clone().json(); //这里是关键,获取所有接口请求成功之后的数据
console.log(res);
if(res?.result) {
const {sacpresult,sucess} = res.result;
if(sucess) {
return sacpresult;
} else {
message.error(res.result.sacpinfo || 'Error')
}
}
return response
};
//统一错误处理
const errorHandler = (error) =>{
const { response } = error;
// console.log(response);
}
export const request = {
// errorHandler,
// 新增自动添加AccessToken的请求前拦截器
requestInterceptors: [authHeaderInterceptor],
responseInterceptors:[demoResponseInterceptors]
};
|