意外的“结束后写入"快递错误 [英] Unexpected "write after end" error in express

查看:46
本文介绍了意外的“结束后写入"快递错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试通过我的服务器代理来自客户端的api调用,以进行某些第三方服务,原因是CORS问题,并在服务器端添加了密钥.我通常通过以下方式完成此任务:

I am trying to proxy an api call from client side through my server for some third party service, reasons for this being CORS issues and adding in a secret key on the server side. I usually get it done in the following way:

app.use('/someService', (req, res) => {
  let url = `https://example.com/${config.SECRET_KEY}/endpoint${req.url}`
  req.pipe(request(url).pipe(res))
})

这样,我可以在客户端使用任何ajax库并执行get请求,例如: get:'/someService/params',它通常会执行并执行该请求,然后进行管道传输回来了.但是现在我开始得到:

this way I can use any ajax library on the client side and perform get request for example: get: '/someService/params' and it would normally go through and perform that request and then pipe it back. However now I started getting:

错误:结束后写

快递,我不确定是什么原因造成的.

in express and I am not entirely sure about what could be causing it.

推荐答案

您的配管错误.现在,您要两次管道传递给 res ( .pipe()返回传递给它的可链接性参数).

Your piping is wrong. As it is now, you're piping to res twice (.pipe() returns the argument passed to it for chainability).

相反,请尝试以下操作:

Instead try this:

req.pipe(request(url)).pipe(res)

但是我应该指出,正确地代理HTTP响应并不是那么简单,因为当前该行将始终以HTTP状态代码200进行响应,而不管用于中间请求的远程服务器如何响应.另外,该响应中的任何标头都不会发送到 res .考虑到这一点,您可以天真的尝试类似的事情:

I should point out however that properly proxying the HTTP response is not quite that simple since currently this line will always respond with HTTP status code 200, no matter what the remote server for the middle request responds with. Also, any headers from that response will not be sent to res. With that in mind, you could naively try something like:

var proxiedRes = req.pipe(request(url));
proxiedRes.on('response', function(pres) {
  res.writeHead(pres.statusCode, pres.headers);
  // You will want to add a `pres` 'error' event handler too in case
  // something goes wrong while reading the proxied response ...
  pres.pipe(res);
});

这篇关于意外的“结束后写入"快递错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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