【问题标题】:Express js res.redirect() from mongoose callback not working来自猫鼬回调的 Express js res.redirect() 不起作用
【发布时间】:2023-03-03 03:27:01
【问题描述】:

我在这里要做的是,

/expense/new页面提交POST请求到/expense/newPost

在 Expressjs 上,这样处理

app.post('/expense/newPost', function(req, res) { ...

继续,使用mongoose 我将集合验证为

tmpExp = new Expense(req.body);

tmpExp.validate(function(err) {
  if(err || !isValidForm) {
    req.session.form.errField =  _.extend(req.session.form.errField, (err.errors || err ));
    req.session.rePop = req.body;
    res.redirect('/expense/new');
  } else {
    console.log('now saving') // successfully logs here.
    tmpExp.save(expPost, function(err2, savedDoc) {
      if(err2) {
        req.session.flash = { 
            global: true
          , css: "error"
          , message: "Internal Server Error"
        }
        res.redirect('/expense/new');
      } else {
        res.redirect('/expense/new?success=' + savedDoc.bill_id);
      }
    });
  }
});

为了清楚起见,我删除了一些验证代码。

现在的问题是,浏览器提交 POST 请求后,数据成功保存在 mongodb 中,但浏览器没有重定向,只是等待服务器响应

【问题讨论】:

  • 如果你查看 Chrome 的网络检查器,你能看到任何 Location 标题吗?代码中的其他内容是否可能已经发送数据?
  • @loganfsmyth 在 Chrome 的网络检查器请求中,newPost 显示待处理 2-3 分钟,然后显示 No data recieved 页面(我的意思是浏览器关闭连接,因为在预定义的时间内没有收到数据)
  • @loganfsmyth 抱歉,实际上服务器在没有发送任何数据的情况下关闭了连接,如 chrome 的No data recieved 页面所示。 Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data
  • 您在处理程序的其他任何地方都没有任何res.end() 调用,对吗?在这里发布可能太多了,但是如果您准备将整个处理程序发布到 JSFiddle 或其他东西中,那么这可能会很有用。
  • @loganfsmyth 我认为您无需在res.redirect() 之后致电res.end(),请参阅对此答案的评论stackoverflow.com/questions/9107226/…

标签: node.js express mongoose


【解决方案1】:

您的保存回调未正确传递。

tmpExp.save(expPost, function(err2, savedDoc) {

应该是:

tmpExp.save(function(err2, savedDoc) {

【讨论】:

    【解决方案2】:

    假设验证码是您从该文件中删除的唯一内容,res 未定义。我建议您只返回 Error 或 null 并在可能存在 res 的父函数中执行其余逻辑。这通常也是一个很好的做法,因为您的模型将是可重用的(模型中没有路径部分)

    【讨论】:

    • 不,这不在模型中,它在 app.post('/expense/newPost', function(req, res) {
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多