nodejs把body的数据解析出来,如何使用http-proxy-middleware做转发

nodejs把body的数据解析出来,如何使用http-proxy-middleware做转发

实现需求

由于最近上线的活动经常被撸羊毛,需要在客户端添加签名,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 );
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值