Nodejs Error: Can't set headers after they are sent

在使用 express 开发的时候出现这个错误:
Error: Can't set headers after they are sent

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:494:11)
    at ServerResponse.setHeader (_http_outgoing.js:501:3)
    at ServerResponse.header (C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\express\lib\response.js:267:15)
    at C:\Users\Zero\Desktop\myBlog\blogAPI\controllers\blogControllers.js:57:13
    at C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\mongoose\lib\model.js:4465:16
    at $__save.error (C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\mongoose\lib\model.js:390:16)
    at C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\kareem\index.js:246:48
    at next (C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\kareem\index.js:167:27)
    at Kareem.execPost (C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\kareem\index.js:217:3)
    at _handleWrapError (C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\kareem\index.js:245:21)
    at C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\kareem\index.js:272:14
    at _next (C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\kareem\index.js:94:14)
    at process.nextTick (C:\Users\Zero\Desktop\myBlog\blogAPI\node_modules\kareem\index.js:452:38)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)

问题原因

在网上查找发现是由于在一次请求后服务器返回两次或者两次以上的响应,这个问题很容易出现在异步回调过程中

解决方案

在每次的请求处理中,一旦服务器返回响应,就及时的使用return,避免出现一次请求后,返回多次响应

if (err) {
   logger.error('delete blog error', err);
   return res.json({
      success: 'false',
      message: err.message
   });
} else {
   res.json({
        success: 'true',
        data: blog
   })
}

具体原因可以参考https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client

你可能感兴趣的:(Nodejs Error: Can't set headers after they are sent)