proxy json requests with node express

纵饮孤独 提交于 2019-12-30 09:46:10

问题


I use the following node-express code to proxy requests from a web server to an API server:

app.use('/api', function(req, res) {
  var url = 'http://my.domain.com/api' + req.url;
  req.pipe(request(url)).pipe(res);
});

This works well for simple requests of any verb (get, post, etc...), however once I send 'Content-type': 'application/json' requests, it hangs on the pipe line.

Why does this simple node-express proxy code hang on json requests?
How can it be altered to support them?


回答1:


You need to move that custom middleware function before this line so that it's executed before any of the body parsers. This makes sure that the request data is still there for piping to request(url) in your custom middleware.

The cause of the hanging currently is that req has no data to write to request(url) (because the body parsing middleware already read all of the request data and parsed it) and so it never calls .end() on the request(url) stream. This means that the request to url never completes because it's just sitting there waiting for data that it will never get.




回答2:


In the case of a post request, the following construct works:

app.post('/api/method', (req, res) => {
  req.pipe(request.post(someUrl, { json: true, body: req.body }), { end: false }).pipe(res);
}

This is of course relevant if you're using the bodyparser middleware.




回答3:


app.use('/api', function(req, res) {
  var url = 'http://my.domain.com/api' + req.url;
  
  request({
          uri: url,
          method: "POST",
          body: _body,
          json: true
      }, function (_err, _res, _resBody) {
          //do somethings
          res.json(_resBody);
      });

});


来源:https://stackoverflow.com/questions/26121830/proxy-json-requests-with-node-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!