我确实看到了一些类似的问题,但九个可以解决我的问题!
在nodeJS Express应用程序中,req.session始终未定义。 在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
答案 0 :(得分:0)
当您使用https://www.npmjs.org/package/csurf中间件
时,将出现CSRF令牌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();
}) ;