一、v5拦截器 requestInterceptors
在umijs的配置中 Interceptor
拦截器主要作用You can intercept requests or responses before they are handled by then or catch.可以先拦截请求或响应,然后再进行捕获或捕获。
requestInterceptors 该配置接收一个数组,数组的每一项为一个 request 拦截器。等同于 umi-request 的 request.interceptors.request.use()。
requestInterceptors: [headerInfo]
在app.tsx中添加上下列拦截器代码。
headerInfo返回一个{url, options},在options的headers上添加上token
const headerInfo: RequestInterceptor = (url: string, options: RequestInit) => {
if (localStorage.getItem('token')) {
const token = `Bearer ` + localStorage.getItem('token');
// options.headers.Authorization = `Bearer ` + localStorage.getItem('token');
options.headers = {
...options.headers,
"Authorization": token,
'Content-Type': 'application/json',
}
}
console.log("url", url);
return { url, options };
}
/**
* 异常处理程序
*/
const errorHandler = (error: ResponseError) => {
const { response } = error;
if (response && response.status) {
const errorText = codeMessage[response.status] || response.statusText;
const { status, url } = response;
notification.error({
message: `请求错误 ${status}: ${url}`,
description: errorText,
});
}
if (!response) {
notification.error({
description: '您的网络发生异常,无法连接服务器',
message: '网络异常',
});
}
throw error;
};
在request的配置RequestConfig中,添加上拦截器
export const request: RequestConfig = {
errorHandler,
credentials: 'include',
requestInterceptors: [headerInfo]
};
二、umi-request 的拦截器
umi官方给的实例 添加拦截,创建客户端请求
import request from 'umi-request';
request.interceptors.request.use(
(url, options) => {
return {
url: `${url}&interceptors=yes`,
options: { ...options, interceptors: true },
};
},
{ global: false }
); // second paramet defaults { global: true }
function createClient(baseUrl) {
const request = extend({
prefix: baseUrl,
});
return request;
}
const clientA = createClient('/api');
const clientB = createClient('/api');
// Independent instance Interceptor
clientA.interceptors.request.use(
(url, options) => {
return {
url: `${url}&interceptors=clientA`,
options,
};
},
{ global: false }
);
clientB.interceptors.request.use(
(url, options) => {
return {
url: `${url}&interceptors=clientB`,
options,
};
},
{ global: false }
);
三、axios拦截请求
// 创建实例
const instance = axios.create({
baseURL: "http://localhost:4000/L1/getData",
timeout: 5000 // 请求超时时间
});
instance.interceptors.response.use(
res => { // 正确则直接返回res
return res;
},
err => { // 对错误进行处理
console.log(err.response)
if (err.response.data.message) {
message.error(err.response.data.message);
if (err.response.status === 401) {
const history = createHistory();
history.push("/login"); // 401noAuthoration则跳转到登录页面
}
}
return Promise.reject(err);
}
);
// 实例请求头添加上token
instance.interceptors.request.use(function(config) {
if (localStorage.token) {
config.headers.Authorization = "Bearer " + localStorage.token;
}
return config;
},function(err) {
return Promise.reject(err);
}
);
// 暴露四种请求方式
// get请求
export function get(url, params) {
return instance.get(url, {
params
});
}
// post请求
export function post(url, data) {
return instance.post(url, data);
}
// put请求
export function put(url, data) {
return instance.put(url, data);
}
// del请求
export function del(url) {
return instance.delete(url);
}
总结
antd-pro对umijs的请求拦截进行了二次封装,实现起来十分方便,添加了token之后还应该判断token的有效时间,查看token是否过期吗,若已过期,则将请求挂起。等待后台刷新token。