我收到以下错误:
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at Array.write (D:\UberGo\node_modules\finalhandler\index.js:285:9)
at listener (D:\UberGo\node_modules\on-finished\index.js:169:15)
at onFinish (D:\UberGo\node_modules\on-finished\index.js:100:5)
at callback (D:\UberGo\node_modules\ee-first\index.js:55:10)
at IncomingMessage.onevent (D:\UberGo\node_modules\ee-first\index.js:93:5)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
我的 Controller :
app.get('/rider/history', function(request, response,next) {
rideHistory=[];
rhController.getAllRides(request.session.riderId, function (err, result) {
if (err) return handleError(err);
if (result.length > 0) {
response.render('rider_history.html',{
rideHistory: JSON.stringify(result),
Title: config.title.history,
moment: moment
});
response.end();
}
});
var Projection = {
__v : false,
_id : false,
};
exports.getAllRides = function(riderId, callback){
rideHistory.find({RiderId: riderId},Projection, callback);
};
当我渲染页面时,它工作正常,但在调用 JSON.stringify()
后,我收到上述错误。我不知道如何解决它或者我做错了什么?
我想将乘客数据显示到 Google map 中,但返回的数据未格式化。-这就是我必须使用 JSON.stringify(stringify) 的原因。
最佳答案
不要同时使用 render 和 end 方法。如果您使用响应方法两次或多次,则会发生错误:发送后无法设置 header
您不需要express中的response.end方法。删除它,然后您的代码就可以工作了。
渲染方法已经包含最终功能。
关于node.js - 错误 : Can't set headers after they are sent after res. 渲染()调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52923099/