Node.js - 页面超时 - 发送后无法设置标头

时间:2013-01-28 15:56:45

标签: javascript node.js express mongoose

我使用mongoose,express,mongodb运行node.js应用程序。我有一个'团队'页面,显示当前数据库中的团队列表,它之前的工作非常好,但是因为我已经添加了下面的代码....我可以导航到pge并查看它,并且之后,如果我刷新页面或尝试再次加载团队页面,页面会超时并且不会加载,但在终端中它会显示GET /team

以下是我添加的代码:

路由/ index.js

var getAllMeta = function(req, res, next){
  Team.getAllMeta(function(err, teamsList){
    if(!err && teamsList){
      req.teamsList = teamsList;
    }
    next(err);
  });
};

  app.get('/team', getAllMeta, function(req, res){
    util.log('Serving request for url[GET] ' + req.route.path);
    if(req.session.user){
      res.render('team', {'teamsList' : req.teamsList} );
    } else {
      res.redirect('/');
    }
  });

HTML代码是.jade,它只包含以下代码以使用teamsList显示团队:

div#teamListDiv
  -if(teamsList.length > 0){
    -each team in teamsList
      a.teamLink(id="#{team.key}", href="#") #{team.name}
      br
  -}else{
    h3 No teams till now..
  -}

所以它工作得很好,但一旦刷新或重新加载,它就会超时并且什么都不做。非常感谢任何帮助。

编辑:让它加载后,这是终端的错误代码

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:645:11)
    at ServerResponse.res.setHeader (/Users/sweetest_viv/nodeapps/tournamentManager/node_modules/express/node_modules/connect/lib/patch.js:59:22)
    at next (/Users/sweetest_viv/nodeapps/tournamentManager/node_modules/express/node_modules/connect/lib/proto.js:162:13)
    at pass (/Users/sweetest_viv/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:107:24)
    at nextRoute (/Users/sweetest_viv/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:100:7)
    at callbacks (/Users/sweetest_viv/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:164:11)
    at Promise.getAllMeta (/Users/sweetest_viv/nodeapps/tournamentManager/routes/index.js:17:5)
    at Promise.addBack (/Users/sweetest_viv/nodeapps/tournamentManager/node_modules/mongoose/lib/promise.js:128:8)
    at Promise.EventEmitter.emit (events.js:96:17)
    at Promise.emit (/Users/sweetest_viv/nodeapps/tournamentManager/node_modules/mongoose/lib/promise.js:66:38)

index.js第17行的代码是

next(err);

在我上面发布的getAllMeta函数中

编辑2:Team.getAllMeta

Team.statics.getAllMeta = function(cb){
  var query = this.find({}, 'key name', cb);
  return query.exec(cb);
};

2 个答案:

答案 0 :(得分:1)

问题是你的中间件

var getAllMeta = function(req, res, next){
  Team.getAllMeta(function(err, teamsList){
    if(!err && teamsList){
      req.teamsList = teamsList;
    }
    next(err);
  });
};

next(err)被称为时间。即使没有错误。 Express会将错误转发给errorHandler,同时您尝试在/team路径上呈现页面。因此错误Can't set headers after they are sent

将以下内容放入if () {}声明

return next();

这会阻止调用next(err)

答案 1 :(得分:1)

问题出在Team.getAllMeta

Team.statics.getAllMeta = function(cb){
  var query = this.find({}, 'key name', cb);
  return query.exec(cb);
};

注意您多次通过cb的方式。它被多次调用,第二次出错。因此,您的行next(err);会触发两次。第一次,它做你想要的。第二次,err是非空的,它转到默认的错误处理程序,它尝试构建有关错误的响应,但由于标题已经被发送而失败,你不能这样做两次。