gpt4 book ai didi

node.js - req.session 未定义nodeJS

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:07 27 4
gpt4 key购买 nike

我尝试在 NodeJS 中设置一个 session ,然后在我的/auth 路由中使用它,但我在 session 中遇到了未定义的问题。

在 app.js 中:

const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./config/DB');

const app = express();
const session = require('express-session')
const MongoStore = require('connect-mongo')(session);

mongoose.connect(config.DB, { useNewUrlParser: true }).then(
() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database' + err) },
options
);
const db = mongoose.connection


const adUnitRoutes = require('./routes/adunit.route');
const userProfileRoutes = require('./routes/userprofile.route');


app.use('/adunits', adUnitRoutes);
app.use('/userprofile', userProfileRoutes);

app.use(session({
secret: 'my-secret',
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: db })
}));

在 route :

userProfileRoutes.route('/authentification').post((req, res) => {

console.log('req session : ' + req.session.userId);
//here I got cant read property of userId because session is undefined

});

最佳答案

发生这种情况是因为您在添加中间件之前设置了路由。您的处理程序本质上是中间件,因此如果它们在 session 之前添加,则您的 session 尚未被处理并添加到请求中。

设置中间件后添加路由将使其按预期工作。

查看这个最小化的示例:

const express = require('express');
const app = express();
const session = require('express-session');

app.get('/broken', (req, res) => {
console.log('req session : ' + req.session.userId);
res.write(String(req.session.userId));
req.session.userId = 1;
res.end();
});

app.use(
session({
secret: 'my-secret',
resave: false,
saveUninitialized: true
})
);

app.get('/ok', (req, res) => {
console.log('req session : ' + req.session.userId);
res.write(String(req.session.userId));
req.session.userId = 1;
res.end();
});

app.listen(8089);

关于node.js - req.session 未定义nodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53216716/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com