获取数据时报错:Can't set headers after they are sent.
发布于 6 年前 作者 maschzh 4754 次浏览 最后一次编辑是 5 年前 来自 问答
http.js:690
    throw new Error('Can\'t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:690:11)
    at ServerResponse.header (/home/maschzh/workspace/u9blogsApp/node_modules/express/lib/response.js:666:10)
    at ServerResponse.json (/home/maschzh/workspace/u9blogsApp/node_modules/express/lib/response.js:232:10)
    at Promise.exports.topicOne (/home/maschzh/workspace/u9blogsApp/controllers/topic.js:65:14)
    at Promise.onResolve (/home/maschzh/workspace/u9blogsApp/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
    at Promise.emit (events.js:95:17)
    at Promise.emit (/home/maschzh/workspace/u9blogsApp/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
    at Promise.fulfill (/home/maschzh/workspace/u9blogsApp/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)
    at schema (/home/maschzh/workspace/u9blogsApp/node_modules/mongoose/lib/query.js:1400:13)
    at model.Document.init (/home/maschzh/workspace/u9blogsApp/node_modules/mongoose/lib/document.js:254:11)

代码:

exports.topicOne = function (req, res, next){
	Topic.findById(req.params.topicId, function (err, topic){
		if(err){
		       return next(err);
		}
		return res.json(topic.doc);
	});
};
5 回复

排查下流程里的所有中间件,会否是在其他的中间件里做了会set headers的操作了但没有 return掉?

代码贴得不够。前面res有返回。

@DavidCai1993 问题已经解决了,在return res.json(topic.doc);之前加设置一下状态就解决了

@maschzh 怎么设置 的

@baoniu 在return res.json(topic.doc);之前加了res.status(200);就可以了

回到顶部