首页 > 解决方案 > 在内部发出另一个 http 请求后发送 http 响应时出错:“发送后无法设置标头”

问题描述

在我的服务器内部发出另一个 http 请求后,我在 Node.js 的 express.js 中发送 http 响应时收到以下错误。

Error: Can't set headers after they are sent.
_http_outgoing.js:491
    at validateHeader (_http_outgoing.js:491:11)
    at ServerResponse.setHeader (_http_outgoing.js:498:3)
    at ServerResponse.header (/home/gustavo/Programacao/node-js/Imobiliaria/node_modules/express/lib/response.js:767:10)
    at ServerResponse.json (/home/gustavo/Programacao/node-js/Imobiliaria/node_modules/express/lib/response.js:264:10)
    at Request._callback (/home/gustavo/Programacao/node-js/Imobiliaria/api/controllers/property.js:71:41)
    at Request.self.callback (/home/gustavo/Programacao/node-js/Imobiliaria/node_modules/request/request.js:185:22)
    at emitTwo (events.js:126:13)
    at Request.emit (events.js:214:7)
    at Request.<anonymous> (/home/gustavo/Programacao/node-js/Imobiliaria/node_modules/request/request.js:1161:10)
    at emitOne (events.js:116:13)

这是我的代码:

var request = require('request');
// ...
// Making http request
request(utils.url('/api/property-photos/' + propertyId), function (error, response, body) {
    // ...
    res.status(200).json({}).end(); // For tests
    // ...
});

我认为该请求正在向我的服务器的响应发送一些响应,但我不知道为什么以及如何。

我想先感谢谁能帮助我。;)

标签: node.jsexpress

解决方案


请求包仅用于发出请求并获得响应。所以你不能发送res.send() 通常这个错误是在你发送 res(response) 2 次或更多次时引起的

导致相同问题的示例。

route.get('/app',(req,res)=>{
 res.send()
 res.send()
})

如果存在类似的内容,请检查您的代码。


推荐阅读