node.js Node + Express + Passport:req.user 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16434893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node + Express + Passport: req.user Undefined
提问by gojohnnygo
My question is similar to this one, but there was no insight into his solution.
我的问题是类似这样的一个,但没有深入了解他的解决方案。
I'm using Passport to auth using Instagram. After successful auth, users are directed to "/". At this point, the request has the user object (aka it's working). However, once I redirect, the req.user is undefined. :'(
我正在使用 Passport 使用 Instagram 进行身份验证。认证成功后,用户被定向到“/”。此时,请求具有用户对象(也就是它正在工作)。但是,一旦我重定向, req.user 就未定义。:'(
The odd part is that passport.deserializeUser is being called with each request. It's successfully getting the user object, but somewhere along the middleware road, req.user is not being set (or being unset).
奇怪的是,每个请求都会调用passport.deserializeUser。它成功地获取了用户对象,但是在中间件道路上的某个地方,没有设置(或未设置)req.user。
// on successful auth, goto "/"
app.get('/', function(req, res) {
// if the request has the user object, go to the user page
if (req.user) {
res.redirect("/user/" + req.user._id);
}
res.render("index");
}
app.get('/user/:uid', function(req, res) {
console.log(req.user) // undefined
}
采纳答案by Martin
Have you set up session state for your app? You need something like this...
您是否为您的应用设置了会话状态?你需要这样的东西......
app.use(session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());
回答by Jon Rodness
My issue was not specifying to send cookies when using fetch on the client-side. It worked after including the credentials: 'include' field in the request.
我的问题不是在客户端使用 fetch 时指定发送 cookie。在请求中包含凭据:“包含”字段后,它起作用了。
fetch('/api/foo', {credentials: 'include'})
回答by leylandjacob
I am super new to Node but it was a middleware issue for me. Added bodyParser and rearranged to fix.
我是 Node 的新手,但对我来说这是一个中间件问题。添加 bodyParser 并重新排列以修复。
Broken code:
损坏的代码:
app.use(express.cookieParser('secret'));
app.use(express.cookieSession());
app.use(express.session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
Working Code:
工作代码:
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
Hope this helps
希望这可以帮助
回答by sanusi
Previously I have these code (did not work):
以前我有这些代码(不起作用):
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser('abcdefg'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
secret: 'abcdefg',
resave: true,
saveUninitialized: false,
cookie: { secure: true } // this line
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
Then I remove the cookie option from session initializer:
然后我从会话初始值设定项中删除 cookie 选项:
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser('abcdefg'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
secret: 'abcdefg',
resave: true,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
and now it works.
现在它起作用了。
回答by Adrian Enriquez
Yeah enable sessions like @Martin says. But if you are using Express 4.* version, middleware like sessions are not bundled so you need to install it individually.
是的,像@Martin 所说的那样启用会话。但是,如果您使用的是 Express 4.* 版本,则不会捆绑会话等中间件,因此您需要单独安装。
- Add "express-session": "1.4.0"in your package.json
- npm install
- use it
- 在 package.json 中添加"express-session": "1.4.0"
- 安装
- 用它
;
;
var express = require('express');
var cookieParser = require('cookie-parser')
var session = require('express-session')
var app = express()
app.use(cookieParser()) // required before session.
app.use(session({secret: 'keyboard cat'}))
For more information check the express session documentation.
有关更多信息,请查看快速会话文档。
回答by ufxmeng
I encounter the same problem because of just copy & paste following code from express-session documentation, but not fully read the documentation.
我遇到了同样的问题,因为只是从 express-session 文档中复制并粘贴以下代码,但没有完全阅读文档。
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
In the documentation, it mentioned:
在文档中,它提到:
However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set.
但是,它需要启用 https 的网站,即安全 cookie 需要 HTTPS。如果设置了安全,并且您通过 HTTP 访问您的站点,则不会设置 cookie。
so if you just have a HTTP connection, remove the secure option,and below code should work:
所以如果你只有一个 HTTP 连接,删除安全选项,下面的代码应该可以工作:
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
//cookie: { secure: true } remove this line for HTTP connection
}))
回答by Strawberry
In routes, try adding: {session: true}
在路由中,尝试添加: {session: true}
app.get('/auto-login', passport.authenticate('cross', {session: true}))
回答by ergusto
I had this exact same problem using express 4 and after trying pretty much everything I could find online I finally managed to get it working by adding 'cookie-session'.
我在使用 express 4 时遇到了完全相同的问题,在尝试了几乎所有可以在网上找到的东西之后,我终于通过添加“cookie-session”设法让它工作。
var cookieSession = require('cookie-session');
app.use(cookieSession({
keys: ['key1', 'key2']
}));
回答by Alain1405
When you authenticate a user, the request value req.useris filled. To know if the identify the user and fill that value, a cookie is used.
If like me, you configure the session with secure cookies, cookies will be available only over HTTPS, which is not the standard configuration for, let's say, a local development server. To have cookies work over HTTP, comment out cookie: { secure: true }and req.uservalue will be properly configured:
当您对用户进行身份验证时,req.user会填充请求值。要知道是否识别用户并填充该值,将使用 cookie。如果像我一样,您使用安全 cookie 配置会话,cookie 将仅在 上可用HTTPS,这不是本地开发服务器的标准配置。要让 cookie 正常工作HTTP,请注释掉cookie: { secure: true }并req.user正确配置值:
this.app.use(session({
resave: true,
saveUninitialized: true,
secret: process.env.SESSION_SECRET || "a secret",
// cookie: { secure: true },
}));
If, reasonably, you want cookies over HTTPSonly in production, you can do something like:
如果,合理地,您只想HTTPS在生产中使用cookie ,您可以执行以下操作:
cookie: { secure: process.env.ENV === 'PRODUCTION' }
回答by Smit Patel
I think everyone has several mistakes on server-side which can cause this problem.
我认为每个人在服务器端都有几个错误可能导致这个问题。
To solve this error, please check these things:
要解决此错误,请检查以下事项:
Check 1 - Passport Serialization and Deserialization
检查 1 - Passport 序列化和反序列化
The correct way to do it (Mongoose):
正确的做法(猫鼬):
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((_id, done) => {
User.findById( _id, (err, user) => {
if(err){
done(null, false, {error:err});
} else {
done(null, user);
}
});
});
Check 2 - Sessions
检查 2 - 会话
Check your cookie-sessionpackage is configured properly and working. Check if you can actually see cookie on client-side. If you are using express-sessionplease make sure you can see session-id in memory or cache(Redis).
检查您的cookie-session包是否配置正确且工作正常。检查您是否真的可以在客户端看到 cookie。如果您使用的是express-session,请确保您可以在内存或缓存(Redis)中看到 session-id。
Check 3 - SSL nginx
检查 3 - SSL nginx
Make sure your reverse proxysupports cookies and request type. Don't forget to check cookie/session configuration [secureflag]
确保您的反向代理支持 cookie 和请求类型。不要忘记检查 cookie/会话配置 [ secureflag]
When I face this error, I was using (user)for callback function. Then I corrected it with (err, user). Now its all right. Cheers
当我遇到这个错误时,我使用的(user)是回调函数。然后我用(err, user). 现在好了。干杯

