[英]Error on sending http response after making another http request inside: “Can't set headers after they are sent”
I'm getting the following error when I send http response, in an express.js in Node.js, after making another http request inside my server. 在服务器中发出另一个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)
Here is my code: 这是我的代码:
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
// ...
});
I think that the request is sending some response to my server'se response, but I can't figure out why and how. 我认为该请求正在向服务器的响应发送一些响应,但是我不知道原因和方式。
I'd like to antecipate my thanks for who can help me. 我要感谢能够帮助我的人。 ;) ;)
request package is only to make request and to get response.So you can not send res.send()
Usually this error caused when you send res(response) 2 or more times request包仅用于发出请求并获得响应。因此,您无法发送res.send()
通常,此错误是在您发送res(response)2次或更多次时引起的
example to cause same problem. 引起同样问题的例子。
route.get('/app',(req,res)=>{
res.send()
res.send()
})
Check in your code if something like this is present. 检查您的代码中是否存在类似的内容。
Thank you for helping me :D 谢谢您的帮助:D
I've just found the issue. 我刚刚发现了问题。 The http request I'm making inside my server current request does it asynchronously. 我在服务器当前请求中发出的http请求是异步执行的。 So after calling it, I was calling res.end()
, before I send a response to my server request. 因此,在调用它之后,在发送对服务器请求的响应之前,我正在调用res.end()
。 This response I am sending inside the other http request results. 我正在其他HTTP请求结果中发送此响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.