【问题标题】:Node + Express + Passport: req.user Undefined but works in PostmanNode + Express + Passport:req.user 未定义但在 Postman 中工作
【发布时间】:2017-08-06 21:30:02
【问题描述】:

我的问题与one 类似,那里的所有答案都没有帮助我。

我正在使用带有本地策略的 Passport.js (passport-local-mongoose)。 下面的中间件适用于 Postman,但每当我从我的 React 客户端尝试时都会失败。

exports.isLoggedIn = (req, res, next) => {
  console.log(req.user) // undefined with react, but works from postman
  if (req.isAuthenticated()) {
    return next();
  }
}

这是我的 app.js:

require('./handlers/passport');
app.use(cors())
app.use(session({
  secret: process.env.SECRET,
  key: process.env.KEY,
  resave: true,
  saveUninitialized: true,
  store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());

handlers/passport.js:

const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('User');

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

user.js(模型):

...
userSchema.plugin(passportLocalMongoose, { usernameField: 'email' });

客户代码:

const url = 'http://localhost:7777/users/<id>';
const config = {
  headers: {
    'Content-Type': 'application/json',
  },
};

axios.put(url, data, config)
  .then(res => console.log(res))
  .catch(err => console.log(err));

我错过了什么吗? passportLocal 策略是否意味着我不能像我的示例那样使用 API 和客户端?谢谢:D

【问题讨论】:

  • 在 React 应用程序中显示您向服务器发送请求的代码。
  • 与普通的 http 调用没有什么不同。我正在使用 axios.js 而不发送任何标头,我已经尝试使用 const headers = { credentials: 'include' };
  • 当您在客户端中对用户进行身份验证时,我不完全确定您是如何处理令牌的。因此,由于您使用的是 axios,因此您需要明确设置您的请求授权,您可以将其包含在后续请求中。检查this
  • 嘿@Rowland,那么我到底需要在我的授权标头中设置什么?这是我第一次使用passport.js,我不知道我应该将什么存储为“令牌”。在我成功/登录后,我可以看到“set-cookie:”属性作为响应头,我可以通过document.cookie访问它,在后续请求中将其发送到服务器也不起作用。

标签: javascript node.js express authentication passport.js


【解决方案1】:

所以,过了一段时间我可以找到答案:

服务器发送 SetCookie 头,然后浏览器句柄来存储它,然后 cookie 与向同一服务器发出的请求一起发送到 Cookie HTTP 头中。

我必须在我的客户端中设置withCredentials: true。 (axios.js)

const config = {
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
};

axios.put(url, { page: '123' }, config)
  .then(res => console.log('axios', res))
  .catch(err => console.log('axios', err));

然后我遇到了 CORS 问题。

所以我将它添加到我的快递服务器:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
    res.send(200);
  } else {
      next();
  }
});

【讨论】:

  • 你是个救命的人。我被困在这里3个小时。你救了我。
猜你喜欢
  • 2013-05-02
  • 2019-02-19
  • 2018-03-28
  • 2021-10-26
  • 1970-01-01
  • 2020-10-17
  • 2016-08-22
  • 2018-05-30
  • 1970-01-01
相关资源
最近更新 更多