重定向请求时生成ERR_HTTP_HEADERS_SENT错误

时间:2018-10-30 19:36:09

标签: node.js rest http express api-design

我正在使用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()方法以便发送请求的标头,因此不确定为什么出现此错误。当查看错误堆栈跟踪时,当我在“数据”事件的回调中调用res.send()方法时,就会出现错误。也许我不了解请求之间的执行流程或发出事件的顺序。任何指导/信息将不胜感激。

1 个答案:

答案 0 :(得分:1)

您不应该在some_string.rfind("/") 事件回调中发送响应,因为响应将在您接收到第一批数据时发送。您应该做的是将data写入响应流,并在chunk事件回调内发送响应:

end