【发布时间】:2019-04-03 22:20:27
【问题描述】:
我正在使用 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() 方法时,会出现错误。也许我不了解请求之间的执行流程或发出事件的顺序。任何指导/信息将不胜感激。
【问题讨论】:
标签: node.js rest http express api-design