node.js - 错误 : Can't set headers after they are sent after res. 渲染()调用

标签 node.js express

我收到以下错误:

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/

相关文章:

node.js - 如何在node js中设置可以在所有twig页面访问的全局变量

node.js - 从运行express-graphql的 Node 服务器发送GraphQLUpload到imagekit.io

javascript - 使用 react-router 并通过 Passport.js 进行身份验证 - 可能吗?

node.js - 手动添加文件到package.json?

node.js - RedisStore - 类型错误 : Cannot read property 'prototype' of undefined

Node.js orm2 - 在 OneToMany 关系中检索新关联时遇到问题

node.js - Github 操作 - 未处理的拒绝 SequelizeConnectionError : no PostgreSQL user name specified in startup packet

javascript - 如何获取将数据(.emit())发送到nodejs服务器的用户的详细信息?

javascript - 在 Node JS 中连接 mysql 和进程变量

javascript - 如何刷新 Firebase session Cookie