节点+快递+护照:req.user未定义,但在邮递员的作品
我的问题类似于这个,所有的答案没有帮助我。
我使用Passport.js本地策略(护照本地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(模型):
... 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
所以,一段时间后我可以find答案:
服务器发送SetCookie头,然后浏览器句柄来存储它,然后发送的Cookie与HTTP 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(); } });