Error: Can't set headers after they are sent.怎么解决?
发布于 10 年前 作者 wangxuq 99808 次浏览 最后一次编辑是 8 年前 来自 问答
E:\nodejs\lianxi\microblog\node_modules\mongodb\lib\mongodb\connection\base.js:245
        throw message;
              ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
    at ServerResponse.res.setHeader (E:\nodejs\lianxi\microblog\node_modules\express\node_modules\connect
\lib\patch.js:63:22)
    at ServerResponse.res.set.res.header (E:\nodejs\lianxi\microblog\node_modules\express\lib\response.js
:527:10)
    at ServerResponse.res.location (E:\nodejs\lianxi\microblog\node_modules\express\lib\response.js:657:8
)
    at ServerResponse.res.redirect (E:\nodejs\lianxi\microblog\node_modules\express\lib\response.js:698:8
)
    at E:\nodejs\lianxi\microblog\routes\index.js:57:9
    at E:\nodejs\lianxi\microblog\models\user.js:31:5
    at E:\nodejs\lianxi\microblog\node_modules\mongodb\lib\mongodb\collection\core.js:119:9
    at E:\nodejs\lianxi\microblog\node_modules\mongodb\lib\mongodb\db.js:1132:7
    at E:\nodejs\lianxi\microblog\node_modules\mongodb\lib\mongodb\db.js:1846:9
10 回复

“Can’t set headers after they are sent.” => “不能发送headers因为已经发送过一次了” => 在处理HTTP请求时,服务器会先输出响应头,然后再输出主体内容,而一旦输出过一次响应头(比如执行过 res.writeHead()res.write()res.end()),你再尝试通过 res.setHeader()res.writeHead() 来设置响应头时(有些方法比如 res.redirect() 会调用 res.writeHead()),就会报这个错误。

(说明:express中的 res.header() 相当于 res.writeHead()res.send() 相当于 res.write()

原因就是你程序有问题,重复作出响应,具体原因很多,需要自己根据以上的原则来排除。

嗯,已经解决了,在一个回调函数前边应该加一个return,谢谢。。

我知道是这个问题。。。然而就是找不到
下班一回来 再翻了一下 一眼就看到了= =

我也是出了这个bug,只有一个res.redirect()方法,找不到其他res.writeHead() 或 res.write() 或 res.end()

加return解决。。。。

@napster99 我是在需要response后

return next()

清除cookie试一下

回到顶部