node 报错信息如下:( Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11) at ServerResponse.header (D:\Hexin\FrontEnd\movie\node_modules\express\lib\response.js:730:10) at ServerResponse.send (D:\Hexin\FrontEnd\movie\node_modules\express\lib\response.js:170:12) at done (D:\Hexin\FrontEnd\movie\node_modules\express\lib\response.js:967:10) at Object.exports.renderFile (D:\Hexin\FrontEnd\movie\node_modules\pug\lib\index.js:422:12) at View.exports.__express [as engine] (D:\Hexin\FrontEnd\movie\node_modules\pug\lib\index.js:465:11) at View.render (D:\Hexin\FrontEnd\movie\node_modules\express\lib\view.js:128:8) at tryRender (D:\Hexin\FrontEnd\movie\node_modules\express\lib\application.js:640:10) at EventEmitter.render (D:\Hexin\FrontEnd\movie\node_modules\express\lib\application.js:592:3) at ServerResponse.render (D:\Hexin\FrontEnd\movie\node_modules\express\lib\response.js:971:7) at D:\Hexin\FrontEnd\movie\app.js:90:9 at Layer.handle [as handle_request] (D:\Hexin\FrontEnd\movie\node_modules\express\lib\router\layer.js:95:5) at next (D:\Hexin\FrontEnd\movie\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (D:\Hexin\FrontEnd\movie\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (D:\Hexin\FrontEnd\movie\node_modules\express\lib\router\layer.js:95:5) at D:\Hexin\FrontEnd\movie\node_modules\express\lib\router\index.js:281:22GET / 404 76.603 ms - 645浏览器报错:路由:控制:(
1 回答
已采纳
ruibin
TA贡献358条经验 获得超213个赞
你的express.js有问题。引入router的位置。必须放在错误处理之前,也就是说 :
app.use(bodyParser.urlencoded({extended: false}));
require('../app/routes/news.server.routes')(app);
app.use(function(req, res, next) {
res.status(404);
try {
return res.json('NOT FOUND');
} catch (e) {
console.error('404 set header after sent');
}
});
app.use(function(err, req, res, next) {
if (!err) {
next()
} else {
res.status(500);
try {
return res.json(err.message || '500 SERVER ERROR');
} catch (e) {
console.error('500 set header after sent');
}
}
});
看见加粗的了吗?后面两个错误处理必须放在最后,因为路由匹配规则是从上到下,匹配到了就终止!
- 1 回答
- 0 关注
- 2174 浏览
添加回答
举报
0/150
提交
取消