目的: 在不修改原有代码的情况下进行网络请求拦截
分析: 在原本的代码中使用哪种网络库进行请求发送不确定
所以将XHR和fetch的请求都进行拦截
开始
首先安装 ajax-hook 和fetch
// fetch拦截
npm install fetch-intercept whatwg-fetch --save
// xhr请求拦截
npm install ajax-hook
// 微信小程序请求拦截
npm install wxapp-api-interceptors
- 添加拦截器
fetchIntercept.ts
import * as fetchIntercept from 'fetch-intercept';
fetchIntercept.register({
// 请求预处理
request: function (url, config) {
console.log("fetch请求前预处理: " + url + " " + config)
return [url, config];
},
// 请求错误预处理
requestError: function (error) {
console.log("fetch请求错误预处理: " + error)
return Promise.reject(error);
},
// 响应预处理
response: function (response) {
// Modify the reponse object
debugger
console.log("fetch响应后预处理: " + response)
return response;
},
//响应错误预处理
responseError: function (error) {
console.log("fetch响应错误预处理: " + error)
return Promise.reject(error);
},
});
- xhrIntercept.ts
import {proxy} from "ajax-hook";
import InterceptHandle from "../intercept/intercept-handle";
proxy({
onRequest: async (config, handler) => {
// 请求前预处理
console.log("请求前预处理: " + config.url + " " + config)
handler.next(config);
},
onError: (err, handler) => {
console.log("错误预处理: " + JSON.stringify(err))
handler.next(err)
},
onResponse: (response, handler) => {
// 响应后预处理
console.log("响应后预处理: " + response.config.url + " " + response)
handler.next(response)
}
});
拦截时需要进行白名单过滤
拦截原理
前端的拦截原理都是类似的