请求拦截处理
备注:
CONF.baseUrl
需要在config->index.js文件中进行配置文章来源:https://www.toymoban.com/news/detail-528763.html
代码如下:文章来源地址https://www.toymoban.com/news/detail-528763.html
import Taro, { Chain } from "@tarojs/taro";
const { brand } = Taro.getSystemInfoSync();
const isDevTools = brand === "devtools";
const IgnoreRoute =[CONF.baseUrl+'/api/user/login/'];
/**
* 响应拦截器
* @param chain
* @returns
*/
const responseInterceptor = function (chain: Chain) {
const requestParams = chain.requestParams;
return chain.proceed(requestParams).then((res) => {
const {data} = res;
// 401身份验证失败
if(data.code === 401 && !IgnoreRoute.includes(requestParams.url)){
Taro.showToast({
title: data.message ,
icon: 'error',
success:()=>{
Taro.redirectTo({
url: `/pages/login/index`,
});
}
});
}
//服务器错误
if(data.code===500){
Taro.showToast({
title: data.message,
icon: 'error',
});
}
return res;
});
};
/**
* 业务拦截器
* 有来接口处理参数,data 统一 {b: string,sign: string, c: string}
* @param chain
* @returns
*/
const interceptor = function (chain: Chain) {
const { requestParams } = chain;
const { url = "", header } = requestParams;
const transferHeader = {
"content-type": "application/json",
...header,
openid: Taro.getStorageSync("openId"),
Authorization: `LAIBAO ${Taro.getStorageSync(TOKEN)}`,
};
if (
["/api"].find((route) =>
url.startsWith(route)
)
) {
requestParams.header = { ...transferHeader };
requestParams.url = `${CONF.baseUrl}${url}`;
return chain.proceed(requestParams).then((res) => res);
}
return chain.proceed(requestParams).then((res) => res);
};
Taro.addInterceptor(interceptor);
Taro.addInterceptor(responseInterceptor);
export interface ResponseType<T> {
code: number;
msg: string;
data?: T;
runtime?: number;
}
export interface ErrorType {
errorCode: number;
errorMsg: string;
}
function httpRequest<T = any, U = any>(option: any): Promise<T> {
const start = +new Date();
return Taro.request<T, U>(option).then((res: any) => {
!isDevTools &&
console.log("request time", +new Date() - start, "ms", option?.url,CONF.baseUrl);
if (res) {
const { code, message } = res?.data;
if (code === 200) {
!isDevTools && console.warn(option, res.data);
return res.data as T;
}
return { code: code, message: message } as unknown as T;
} else {
return res as T;
}
});
}
export default httpRequest;
到了这里,关于Taro+VantUI请求拦截处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!