ERR_HTTP_HEADERS_SENT 重定向请求时发生错误

ERR_HTTP_HEADERS_SENT Error Generated When Redirecting Requests

我正在使用 Node.js 框架和 Express 模块编写一个 API 包装器,将请求重定向到另一台服务器。我可以成功地将请求重定向到目标服务器,并且收到包含 JSON 负载的有效响应。但是,在初始请求之后,如果我尝试另一个请求,我会收到以下错误。

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

这是我为 HTTP GET Express 路由编写的代码示例:

app.get('/companyrecords/:name', function(req, res) {

  const options = {
    protocol: 'http:',
    hostname: 'myhost',
    port: 5001,
    method: 'GET',
    path: '/path/to/resource/?name=name',
    auth: 'username:password',
    headers: {
      Connection: 'close'
    }
  }

  const myAppReq = http.request(options, (myAppRes) =>{
    console.log(`STATUS: ${myAppRes.statusCode}`);
    myAppRes.on('data', (chunk) => {
      console.log(`BODY: ${chunk}`);
      res.send(chunk);
    });
        myAppRes.on('end', () => {
        res.end('No more data to send.');
    });
  });

  myAppReq.on('error', (err) => {
    console.error(`Problem with request: ${err.message}`);
  });

  myAppReq.write('');
  myAppReq.end();
});

不确定为什么会出现此错误,因为我正在调用 req.write() 方法以便发送请求的 headers。当查看错误堆栈跟踪时,当我在 'data' 事件的回调中调用 res.send() 方法时,似乎发生了错误。也许我不了解请求之间的执行流程或事件发出的顺序。任何 guidance/information 将不胜感激。

您不应该在 data 事件回调中发送响应,因为响应将在您收到第一个数据块时发送。你应该做的是将 chunk 写入响应流并在 end 事件回调中发送响应:

const myAppReq = http.request(options, (myAppRes) =>{
    myAppRes.on('data', (chunk) => {
      res.write(chunk);
    });
    myAppRes.on('end', () => {
      res.end();
    });
});