【问题标题】:node leads to homepage even without app.get('/',即使没有 app.get('/',
【发布时间】:2018-07-09 13:05:05
【问题描述】:

我是编码新手,如果我的问题是转储,我很抱歉。我使用带本地策略的passport.js,在返回主页时遇到了保持登录状态的问题。所以我尝试添加一个 req.user:

app.get('/', function(req,res){
  if(req.user){
    console.log('user session is alive')
    .....
  }
  return res.sendFile(__dirname+'/index.html');
});

但是“用户会话还活着”根本没有显示。继续实验,我发现即使我将代码转换为:

app.get('/', function(req,res){
  if(req.user){
    console.log('user session is alive')
    .....
  }
  res.send('Hello world');
});

或将以上代码注释在:

/* app.get('/'....

});*/

node 继续将 index.html 显示为主页。 我错过了什么;不应该 app.get('/'...) 是显示主页的必要路线吗?如何在导致 index.html 之前添加 req.user 请求;谢谢

【问题讨论】:

  • 你确定你没有app.use(express.static(...吗?
  • 听起来你的代码中有express.static。那就是直接暴露包含你的index.html的目录。
  • 是的,我有,你是对的......所以我认为该节点不能作为默认搜索 index.html 的 apache 服务器工作

标签: node.js passport.js


【解决方案1】:

Req.user 只会在那里,如果您在获取请求中将用户对象发送到“/”的路由

您可以从前端发送用户对象,例如使用 axios。

const axios = require('axios');

axios.get('/', {
  user: {
    ID: 12345
  }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

【讨论】:

  • 好的,我同意。但是你如何解释另一个;
  • if 语句没有被计算,但其余的都是,所以在这种情况下 res.send。
  • req.user 如果请求包含 cookie 而不是用户对象,则将存在。基于cookie,passport.js 会将用户的对象加载到req.user
猜你喜欢
  • 1970-01-01
  • 2021-03-07
  • 1970-01-01
  • 2015-09-15
  • 2019-06-27
  • 2013-03-04
  • 2015-12-17
  • 2014-06-29
  • 2013-10-01
相关资源
最近更新 更多