req.session 在节点中未定义?
req.session is undefined in Node?
我已经查看了类似问题的其他答案,但其中 none 对我有用。我编写了两段代码,一段用于测试 cookie 是否正常工作 (cookieTest.js),另一段用于实际使用它们 (users.js)。我尝试移动会话中间件和 cookie 中间件的 app.use() 语句无济于事。关于如何解决这个问题有什么想法吗?
users.js
//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect("MY_DB");
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')
var User = require('../models/user.js');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var uuid = require('node-uuid');
var cookieParser = require('cookie-parser');
//Express Setup
var express = require('express');
var router = express.Router();
var app = express();
var expressValidator = require("express-validator");
var session = require('express-session');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: '_secret_', cookie: { maxAge: 60 * 60 * 1000 }, saveUninitialized: false, resave: false}))
//Routes
router.get('/register', function(req, res){
res.sendFile(appDir + "/views/register.html");
})
router.post('/register', function(req, res) {
req.check('name', 'Name must be Filled in').notEmpty();
req.check('email', 'Email must be Filled in').notEmpty();
req.check('email', "Invalid Email").isEmail();
req.check('password', 'Password Field must be Filled in').notEmpty();
req.check('password', 'Passwords do not Match').equals(req.body.password2)
var errors = req.validationErrors();
if(errors) res.send(errors)
else{
var newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
info: req.body.user_bio
});
User.createUser(newUser, function(err, user){
if(err) throw err;
});
res.redirect('../')
}
})
router.get('/login', function(req, res){
res.sendFile(appDir + "/views/login.html");
})
router.post('/login', function(req, res){
var email = req.body.email;
var candidatePass = req.body.password;
User.findOne({ 'email': email }, 'password id', function (err, user) {
if (err) return handleError(err);
User.checkPassword(candidatePass, user.password, function(err, isMatch){
if(err) throw err;
if(!isMatch) res.end('Password Incorrect!');
else{
req.session.userId = user.id;
res.redirect('../');
}
})
})
})
//Exports
module.exports = router;
当我 运行 时,我得到错误 TypeError: Cannot set property 'userId' of undefined
,这意味着 req.session 未定义。但是,当我 运行 这个时,它工作正常
var express = require('express');
var session = require('express-session');
var app = express();
var uuid = require('node-uuid');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Use the session middleware
app.use(session({
secret: 'jaredasch',
cookie: { maxAge: 60 * 60 * 1000 },
saveUninitialized: false,
resave: false
}))
// Access the session as req.session
app.get('/', function(req, res, next) {
var sess = req.session
if (sess.uuid) {
res.setHeader('Content-Type', 'text/html');
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.write('<form method = \'POST\'action = \'/\'><button type = \'submit\'></form>');
res.end()
} else {
sess.uuid = uuid.v4();
res.setHeader('Content-Type', 'text/html');
res.write('Set Up Session \n')
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.end('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
}
})
app.post('/', function(req,res){
req.session.destroy(function(err) {
if(err) throw err;
console.log('Session Destroyed')
})
res.redirect('/');
})
app.listen(3000, function(){
console.log('Listening on Port 3000')
});
为什么这个行得通而上面那个不行,我该如何解决上面那个?您建议如何解决此类问题?
尝试使用 app.use(cookieParser("_secret_"));
以便它与 Express
的秘密相同
我已经查看了类似问题的其他答案,但其中 none 对我有用。我编写了两段代码,一段用于测试 cookie 是否正常工作 (cookieTest.js),另一段用于实际使用它们 (users.js)。我尝试移动会话中间件和 cookie 中间件的 app.use() 语句无济于事。关于如何解决这个问题有什么想法吗?
users.js
//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect("MY_DB");
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')
var User = require('../models/user.js');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var uuid = require('node-uuid');
var cookieParser = require('cookie-parser');
//Express Setup
var express = require('express');
var router = express.Router();
var app = express();
var expressValidator = require("express-validator");
var session = require('express-session');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: '_secret_', cookie: { maxAge: 60 * 60 * 1000 }, saveUninitialized: false, resave: false}))
//Routes
router.get('/register', function(req, res){
res.sendFile(appDir + "/views/register.html");
})
router.post('/register', function(req, res) {
req.check('name', 'Name must be Filled in').notEmpty();
req.check('email', 'Email must be Filled in').notEmpty();
req.check('email', "Invalid Email").isEmail();
req.check('password', 'Password Field must be Filled in').notEmpty();
req.check('password', 'Passwords do not Match').equals(req.body.password2)
var errors = req.validationErrors();
if(errors) res.send(errors)
else{
var newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
info: req.body.user_bio
});
User.createUser(newUser, function(err, user){
if(err) throw err;
});
res.redirect('../')
}
})
router.get('/login', function(req, res){
res.sendFile(appDir + "/views/login.html");
})
router.post('/login', function(req, res){
var email = req.body.email;
var candidatePass = req.body.password;
User.findOne({ 'email': email }, 'password id', function (err, user) {
if (err) return handleError(err);
User.checkPassword(candidatePass, user.password, function(err, isMatch){
if(err) throw err;
if(!isMatch) res.end('Password Incorrect!');
else{
req.session.userId = user.id;
res.redirect('../');
}
})
})
})
//Exports
module.exports = router;
当我 运行 时,我得到错误 TypeError: Cannot set property 'userId' of undefined
,这意味着 req.session 未定义。但是,当我 运行 这个时,它工作正常
var express = require('express');
var session = require('express-session');
var app = express();
var uuid = require('node-uuid');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Use the session middleware
app.use(session({
secret: 'jaredasch',
cookie: { maxAge: 60 * 60 * 1000 },
saveUninitialized: false,
resave: false
}))
// Access the session as req.session
app.get('/', function(req, res, next) {
var sess = req.session
if (sess.uuid) {
res.setHeader('Content-Type', 'text/html');
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.write('<form method = \'POST\'action = \'/\'><button type = \'submit\'></form>');
res.end()
} else {
sess.uuid = uuid.v4();
res.setHeader('Content-Type', 'text/html');
res.write('Set Up Session \n')
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.end('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
}
})
app.post('/', function(req,res){
req.session.destroy(function(err) {
if(err) throw err;
console.log('Session Destroyed')
})
res.redirect('/');
})
app.listen(3000, function(){
console.log('Listening on Port 3000')
});
为什么这个行得通而上面那个不行,我该如何解决上面那个?您建议如何解决此类问题?
尝试使用 app.use(cookieParser("_secret_"));
以便它与 Express