【问题标题】:Why does (passport) middleware function fire with app.get, but not app.post为什么 (passport) 中间件函数使用 app.get 触发,而不是 app.post
【发布时间】:2017-12-14 21:57:37
【问题描述】:

我有以下中间件功能:

function isLoggedIn(req, res, next) {

  if (req.isAuthenticated()) {
    console.log('***User is logged in***');
    next();
  } else {

    res.redirect('/');
    console.log('***User IS NOT logged in***');
  }
}

这在以下 GET 路由中工作得很好:

app.get('/profile', isLoggedIn, function(req, res) {
    res.render('profile.ejs', {
      user: req.user // get the user out of session and pass to template
    });
  });

但是,当我尝试将 isLoggedIn 函数插入 POST 路由时,它不会触发:

app.post('/add', isLoggedIn, function(req, res) {
    console.log('Success');
  });

为什么我的函数不使用 app.post 触发,但使用 app.get 触发?

【问题讨论】:

    标签: node.js express middleware passport.js


    【解决方案1】:

    如果您使用 jQuery 或 Axios 之类的 promise 库发布到 url,那么 res.redirect 不会更改浏览器所在的页面。在这种情况下,您需要处理导致状态代码为 302(Expresses 重定向的默认状态代码返回)的帖子响应,然后将页面重定向到您需要的位置(在前端)

    【讨论】:

    • 它甚至没有到达代码的 res.redirect 部分,该函数根本没有在 POST 请求上触发。我可以在上述路由 (/add) 中将 app.post 更改为 app.get,并且 isLoggedIn 函数触发(我看到消息打印到控制台)。当我将它改回 .post 时,该函数根本不再触发。
    猜你喜欢
    • 2021-03-04
    • 2016-06-24
    • 2019-05-12
    • 2021-07-24
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多