setheader gives error: “throw new Error('Can\\'t set headers after they are sent.');”

泄露秘密 提交于 2019-12-06 11:59:40

Take a look at the line #4:

if(err) res.serverError(err);

The thing is, res.serverError sends headers already, so since you are not interrupting the execution on it, any of the following calls can cause your error: res.serverError, res.send, res.redirect.

In your particular case it's the redirection. The corresponding line in the backtrace:

...
at ServerResponse.res.redirect (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:698:8)
...

Long story short, the quick fix would be adding return to the forth line:

if (err) return res.serverError(err);

That said, there's no guarantee everything else will work seamlessly.

In a complex code whenever you want to send a response at many occasion you can put a check res.headersSent is false.

IE:if(res.headersSent){res.send()}

if you used "return" before wile sending response then the code will not execute further.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!