使用request.js代理post失败的问题

前面写过一篇使用request.js做代理的文章,可能眼睛敏锐的朋友已经看出在代理POST方法时和代理其它请求方式是有区别的, 现在我来说一下为什么要这么处理。

相信很多人都采用这种方式去代理POST方法,但是你有可能代理不过去,请求会被挂起!

req.pipe(request({
    method: 'POST',
    uri: 'http://localhost:8080/api'
})).pipe(res);

为什么呢?

因为你可能使用了body-parse中间件

require('body-parser').urlencoded({extended: false})

解决方案:

  1)删除urlencoded中间件

  2)改用如下方式代理(取出body后重新组装发送)

request.post({
     uri: 'http://localhost:8080/api',
     form: req.body
}).pipe(res);

参考文献:

  https://github.com/request/request/issues/1664

原文地址:https://www.cnblogs.com/zhen-rh/p/7475080.html