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

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

问题描述

我正在尝试通过我的服务器为某些第三方服务代理来自客户端的 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: '/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).

试试这个:

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天全站免登陆