Node + Express + Passport:req.user未定义但适用于Postman

时间:2017-08-06 21:30:02

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

我的问题类似于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());

处理程序/ 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(model):

...
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

1 个答案:

答案 0 :(得分:3)

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

服务器发送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();
  }
});