Browse Source

feat(请求拦截): 添加请求前后拦截功能并完善请求头处理

- 在afterResponse.js中添加响应后拦截函数调用
- 在index.js中补充请求配置类型定义
- 在api/index.js中为getUserByXcxAPPOpenIdApi添加响应后处理逻辑
- 在beforeRequest.js中完善请求头处理并添加请求前拦截函数调用
master
wei 6 days ago
parent
commit
4d32f1dc51
  1. 8
      libs/api/index.js
  2. 2
      libs/request/afterResponse.js
  3. 19
      libs/request/beforeRequest.js
  4. 4
      libs/request/index.js

8
libs/api/index.js

@ -245,7 +245,12 @@ export function getUserByXcxAPPOpenIdApi(data) {
errorMessage: "微信用户",
method: "POST",
data,
header: { "content-type": "application/x-www-form-urlencoded;charset=utf-8" },
url: "/user/getUserByXcxAPPOpenId.do",
afterResponse(config, response) {
uni.setStorageSync("session", response.header.session);
uni.setStorageSync("X-Header-Token", response.header.session);
},
});
}
@ -319,6 +324,9 @@ export function addCartApi(data = {}) {
errorMessage: "购物车",
method: "POST",
data,
header: {
"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
},
url: "/cart/add.do",
});
}

2
libs/request/afterResponse.js

@ -42,5 +42,7 @@ export async function afterResponse(config, response) {
// throw new ServiceFailError(response.data);
// }
config?.afterResponse?.(config, response);
return response.data;
}

19
libs/request/beforeRequest.js

@ -10,6 +10,10 @@ const BASE_URL = "https://xcx.dgscdw.com/food.shop.api";// 正式服务
// var baseUrl = 'http://www.seelight.top/food.shop.api' //刘盛广
/** 请求拦截 */
/**
* 处理请求前的拦截
*/
export async function beforeRequest(config) {
// 处理 params 拼接到 请求接口中
if (config.params) {
@ -19,7 +23,8 @@ export async function beforeRequest(config) {
// 处理请求头部
config.header = {
...config.header,
session: uni.getStorageSync("session") || "",
"session": uni.getStorageSync("session") || "",
"X-Header-Token": uni.getStorageSync("session") || "",
// tenant_id: uni.getStorageSync("tenantId") || "10001",
// version: "2.0",
};
@ -41,11 +46,13 @@ export async function beforeRequest(config) {
config.url = `${base_url}${config.url}`;
// 挂载token
if (config._with_token !== false) {
if (!config.data)
config.data = {};
// config.data.TOKEN = getToken();
}
// if (config._with_token !== false) {
// if (!config.data)
// config.data = {};
// config.data.TOKEN = getToken();
// }
config?.beforeRequest?.(config);
return config;
}

4
libs/request/index.js

@ -1,3 +1,4 @@
/* eslint-disable max-len */
import { afterResponse } from "./afterResponse";
import { beforeRequest } from "./beforeRequest";
@ -22,6 +23,9 @@ import { beforeRequest } from "./beforeRequest";
* @property {string} errorMessage - 错误定位, 留空则不启用
* @property {string} method - 请求方法默认为 "GET"
* @property {headerType} header - 请求头
* @property {object} data - 请求体数据
* @property {(config: configType) => configType} beforeRequest - 请求前拦截函数参数为configType返回值为configType
* @property {(config: configType, response: any) => any} afterResponse - 响应后拦截函数参数为configType和响应数据返回值为处理后的响应数据
*/
/**

Loading…
Cancel
Save