有的时候我们经常需要拦截应用程序的http/https请求进行额外操作,阿里出品的开源库anyproxy是目前比较易用的开源解决方案,而且支持https证书替换
我是把anyprox当作npm模块来使用的这样可以提供最大的灵活性
const AnyProxy = require('anyproxy');
const options = {
/*忽略请求过程中的证书错误*/
dangerouslyIgnoreUnauthorized: true,
port: 8001,
rule: {
/*请求发起前会被调用*/
*beforeSendRequest(requestDetail) {
return {}
/*修改请求协议,如强制改用https发起请求
return {
protocol: 'https'
};*/
/*修改请求参数
var newOption = Object.assign({}, requestDetail.requestOptions);
newOption.path = '/redirect/to/another/path';
return {
requestOptions: newOption
};*/
/*修改请求body*/
/*return {
requestData: 'my new request data'
//这里也可以同时加上requestOptions
};*/
/*直接返回客户端,不再发起请求,其中statusCode header 是必选字段*/
/*return {
response: {
statusCode: 200,
header: { 'content-type': 'text/html' },
body: 'this could be a <string> or <buffer>'
}
};*/
},
/*返回true表示替换这个https请求的证书并且拦截*/
*beforeDealHttpsRequest(){
return new Promise((resolve, reject) => {
resolve(true);
});
},
/*修改返回数据*/
*beforeSendResponse(requestDetail, responseDetail) {
const newResponse = responseDetail.response;
return new Promise((resolve, reject) => {
resolve({ response: newResponse });
});
},
},
webInterface: {
enable: true,
webPort: 8002,
wsPort: 8003,
},
throttle: 10000,
forceProxyHttps: true,
silent: false
};
const proxyServer = new AnyProxy.ProxyServer(options);
proxyServer.start();