gpt4 book ai didi

node.js - NodeJS Expres + RedisStore ,请求 session 始终未定义

转载 作者:可可西里 更新时间:2023-11-01 11:39:16 24 4
gpt4 key购买 nike

我确实看到了一些类似的问题,但是九个可以解决我的问题!

req.session 在 nodeJS Express 应用中总是未定义的。在 express/connect-redis/和 express-session 包上使用最新版本。

var express = require('express') ;
var app = express() ;
var port = process.env.PORT || 8008 ;
var mongoose = require('mongoose') ;
var cookieParser = require('cookie-parser') ;
var bodyParser = require('body-parser');
var session = require('express-session') ;
var RedisStore = require('connect-redis')(session);
var Hash = require('password-hash') ;
var helmet = require('helmet') ;


app.use(express.static(__dirname + "/view" )) ;
app.use(cookieParser() );
app.use(bodyParser()) ;
app.use(session({
saveUninitialized: true,
resave: true ,
store: new RedisStore({
host: 'localhost',
port: 7379,
db: 2,
pass: 'somePassworD'
}),
secret: 'someSecret' ,
//cookie: { secure: true}
})
);

app.use(helmet()) ;
app.use(function (req, res, next) {
res.locals.csrftoken = req.session._csrf;
next();
}) ;

错误信息:

TypeError: Cannot read property '_csrf' of undefined

最佳答案

当您使用 https://www.npmjs.org/package/csurf 时,CSRF token 将出现中间件

var express = require('express') ;
var app = express() ;
var port = process.env.PORT || 8008 ;
var csrf = require('csurf')
var mongoose = require('mongoose') ;
var cookieParser = require('cookie-parser') ;
var bodyParser = require('body-parser');
var session = require('express-session') ;
var RedisStore = require('connect-redis')(session);
var Hash = require('password-hash') ;
var helmet = require('helmet') ;


app.use(express.static(__dirname + "/view" )) ;
app.use(cookieParser() );
app.use(bodyParser()) ;
app.use(session({
saveUninitialized: true,
resave: true ,
store: new RedisStore({
host: 'localhost',
port: 7379,
db: 2,
pass: 'somePassworD'
}),
secret: 'someSecret' ,
//cookie: { secure: true}
})
);

app.use(csrf());

app.use(helmet()) ;
app.use(function (req, res, next) {
res.locals.csrftoken = req.session._csrf;
next();
}) ;

关于node.js - NodeJS Expres + RedisStore ,请求 session 始终未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26021012/

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