实现需求
由于最近上线的活动经常被撸羊毛,需要在客户端添加签名,node端进行验证,加签的方式是对接口发送的参数进行加密,node端进行解密验证。get 请求的时候没什么问题,但是 post 请求会报 ECONNRESET 错误
错误代码
const proxyMiddleware = require('http-proxy-middleware');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
let Proxy = proxyMiddleware('/otherApi/**', {
target: 'https://xxx.xxx.xxx',
pathRewrite: { '/otherApi': '/api' },
ws: false,
changeOrigin: true,
onProxyReq: function (proxyReq, req, res, target) {
console.log('----代理地址----');
console.log(target.target.href + proxyReq.path);
},
onProxyRes: function (proxyRes, req, res) {
},
onError: function (err, req, res) {
res.json({code: '-998', msg: '转发异常', action: req.path});
}
});
app.use(Proxy );
修正后的代码
修改后post,get,put,delete,文件上传下载都可以
const proxyMiddleware = require('http-proxy-middleware');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
let Proxy = proxyMiddleware('/otherApi/**', {
target: 'https://xxx.xxx.xxx',
pathRewrite: { '/otherApi': '/api' },
ws: false,
changeOrigin: true,
onProxyReq: function (proxyReq, req, res, target) {
console.log('----代理地址----');
console.log(target.target.href + proxyReq.path);
if (req.body && Object.getOwnPropertyNames(req.body).length) {
let bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type','application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
},
onProxyRes: function (proxyRes, req, res) {
},
onError: function (err, req, res) {
res.json({code: '-998', msg: '转发异常', action: req.path});
}
});
app.use(Proxy );