umi-request内部会对后端返回的信息进行拦截;如果想获得后端返回的原始的response;可以使用response.clone().json()
import request, { RequestOptionsInit } from 'umi-request';
const Request = request;
// 请求拦截器
Request.interceptors.request.use((url, options) => {
if (!options?.NoNProgress) NProgress.start();
const headers: RequestOptionsInit = {};
const token = localStorage.getItem('token');
!!token && (headers.Authorization = `Bearer ${token}`);
if (options.resBlob) {
headers.responseType = 'blob';
}
return {
url,
options: {
showErrorMessage: true,
...options,
headers,
currentPathName: history.location.pathname,
ignoreInterceptPathName: ['/login', '/account-settings'],
},
};
});
// 响应拦截器
Request.interceptors.response.use(async (response, options) => {
if (!options?.NoNProgress) NProgress.done();
if (
response.status === ApiCode.UNAUTHORIZED &&
!options.ignoreInterceptPathName.includes(options.currentPathName)
) {
history.push(Routes.LOGIN.path);
} else {
const data = await response.clone().json();
if (data.code !== ApiCode.SUCCESS) {
if (!!~response.url.indexOf(LoginApiUrl)) {
// !options?.ignoreError 防止刷新token报密码错误
if (!options?.ignoreError) Store.dispatch(updateLoginIsSuccess(false));
}
}
}
return response;
});