在React(ES6)中访问护照的req.user? API调用返回req.user未定义
我正在使用使用Passport进行身份validation的React Starter Kit制作应用程序。 我现在正在尝试在前端访问req.user对象的阶段,但是我无法将req.user
对象传递到React / ES6环境。
我试图把这个东西作为一个prop
和context
来使用,但都无济于事。 此时,我决定创build一个API端点,在那里我可以将req.user的值作为JSON返回,但req.user
被返回为undefined
,尽pipe在get('*')
下工作正常。
这是我所做的GET调用,即返回undefined
:
server.get('/user', (req, res) => { console.info('user: ', req.user); });
而
server.get('*', async (req, res, next) => { console.info('*: ', req.user); // ... the rest of the React Starter Kit rendering code
确实会返回req.user
的对象,这让我感到困惑。 护照会限制在某些网站吗?
中间件:
server.use(express.static(path.join(__dirname, 'public'))); server.use(cookieParser()); server.use(session({ secret: 'keyboard cat', cookie: { httpOnly: false }, resave: true, saveUninitialized: true, })); server.use(passport.initialize()); server.use(passport.session());
序列化/反序列化就像他们得到的一样简单:
passport.serializeUser((user, done) => { console.log('serializeUser'); done(null, user); }); passport.deserializeUser((obj, done) => { console.log('deserializeUser'); done(null, obj); });
我知道还有类似的SO线程关于req.user
是未定义的,但似乎没有我的情况,它有时只是根据请求的位置不确定。 感谢您的阅读和任何build议。 干杯!
编辑:这是validationstream程
[initial app load with fresh server instance...] in (*) passport FALSE indexPage mounting... in (/user) passport FALSE [click login button and successfully login] serializeUser deserializeUser in (*) passport is TRUE indexPage mounting... in (/user) passport FALSE
我做了一些进一步的testing,并发现了一些有趣的事情,当触发与Chrome控制台的API调用。 我正在使用fetch
来做到这一点 – 我做fetch('/user')
然后在componentDidMount
方法中logging响应。 现在,当我在Chrome控制台中执行此操作时: fetch(/*)
,terminal控制台loginin (*) passport is false
再次in (*) passport is false
。
所以问题似乎是护照在初始渲染后完全消失。 Cookie的问题可能? 我要进一步调查,看看我能find什么。
与使用XMLHttpRequest()
类似,使用fetch()
,需要明确告诉浏览器需要与请求一起发送任何凭证(例如会话cookie,Passport需要哪些凭证以识别活动会话):
fetch('/user', { credentials : 'same-origin' }).then(...);
这里logging了您可以使用的各种值。
- 何时应该使用error handling中间件function
- 使用Typescript扩展快速请求对象
- 如何在express / nodejs中添加标题到静态gzip文件?
- Node.js Express App – Rickshaw.Graph.RangeSlider TypeError:$(element).slider不是函数
- 在Mongoose中find一个子文档
- 发送后无法设置标题。 Nodejs /用axiosexpression
- 无法获取Node.js Express代码在Cloud 9中说'Hello World'
- 你如何将用户redirect到node.js中的另一个链接?
- Node-MySQL – Query()方法中的转义与Mysql.Escape()/ Mysql.EscapeId()