【问题标题】:Does express provides different req and res objects for each individual request?express 是否为每个单独的请求提供不同的 req 和 res 对象?
【发布时间】:2016-03-08 18:30:15
【问题描述】:

我使用Express Router如下图

router.post('/do', function(req, res, next) {
   // some sample code
   var questions = new Questions();
   questions.display(req, res); 
});

display 函数负责调用 res.send

在上面的 sn-p 中,我正在创建 Questions 的实例并将 req, res 对象传递给它。

现在从我的sample.js 文件中,我向同一条路由发出了近 5 个 ajax 请求,只有一个请求成功,之后我收到错误

Can't set headers after they are sent.

所以我不确定为什么会收到此错误!。

有人可以帮忙吗?

更新

显示函数中的代码

Questions.prototype.display = function(req, res) {

  // Check if type of question exists
  if (req.body.questionType) {
    res.send({message: 'No Type found in request body!'});
  } else {
    // logic for getting questions from DB based on question type
    return res.send(questions);
  }
}

【问题讨论】:

  • 当您将 req 传递给您的问题时,您的函数会接受请求。假设您打印的错误来自您的快速服务器,那么从您的问题和 question.display() 中查看附加代码会很有用。我正在以相同的方式使用快速路由器运行服务器,并且在构建某些页面时向同一个端点运行了 10 个请求,它工作得很好,所以这应该不是问题。
  • @Robin:已更新代码。
  • 我不确定您是否仍将 req, res 传递到 Questions 中? var questions = new Questions(); questions.display(req, res);
  • @RistoNovik:更新了问题。我将reqres 传递给显示方法。
  • 嗯,缺少一些代码,您已经通过某种方式发送了响应。还要从 post 处理函数中删除下一个你是否也在使用其他中间件?

标签: node.js express


【解决方案1】:

将请求更改为 req:

router.post('/do', function(req, res, next) {
// some sample code
var questions = new Questions(req, res);
questions.display(); 

});

this

【讨论】:

  • 糟糕,我尝试了不同的方法。当时它仍然是request,但现在又更新了。
  • 在 res.send({message: 'No Type found in request body!'}) if (req.body.questionType) { return res.send({message: 'No Type found在请求正文中!'}); } else { // 根据问题类型从数据库获取问题的逻辑 return res.send(questions); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 2014-12-26
  • 1970-01-01
  • 2012-09-13
相关资源
最近更新 更多