代理json请求与节点express [英] proxy json requests with node express

查看:102
本文介绍了代理json请求与节点express的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下节点代码来代理从Web服务器到API服务器的请求:

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

这对于任何动词(get,post等等)的简单请求都有效一旦我发送'Content-type':'application / json'请求,它挂在管上行。 / p>

为什么这个简单的节点代理代码挂起在json请求?

如何更改支持他们?

解决方案

您需要在之前移动该自定义中间件功能 a href =https://github.com/DaftMonk/fullstack-demo/blob/72cf7510244c577a0ed4d139cfa6fd4922ddd47d/server/app.js#L28>此行,以便它在任何身体解析器之前执行。这可以确保您的自定义中间件中的请求数据仍然存在于请求(url)中。



目前挂起的原因是 req 没有数据写入 request(url)(因为身体解析中间件已经读取所有请求数据并解析它),所以它从来没有在请求(url) .end() $ c>流。这意味着请求 url 从来没有完成,因为它只是坐在那里等待它永远不会得到的数据。


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?

解决方案

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.

这篇关于代理json请求与节点express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆