[英]Node + Express + Passport: req.user Undefined but works in Postman
我的問題是,類似這樣的一個 ,有所有的答案沒有幫助我。
我正在將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(模型):
...
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));
我想念什么嗎? passwordLocal策略是否意味着我不能像我的示例那樣使用API和客戶端? 感謝:D
因此,一段時間后,我可以找到答案:
服務器發送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();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.