我正在使用express-session-sequelize。
server.js
var http = require('http'),
express = require('express'),
app = express(),
config = require('./config/config'),
routes = require('./src/routes'),
bodyParser = require('body-parser'),
session = require('express-session'),
application = require("./src/application");
path = require('path');
const expressSession = require('express-session');
const SessionStore = require('express-session-sequelize')(expressSession.Store);
const Sequelize = require('sequelize');
const myDatabase = new Sequelize('db', 'root', '', {
host: 'localhost',
dialect: 'mysql'
});
const sequelizeSessionStore = new SessionStore({
checkExpirationInterval: 15 * 60 * 1000, // The interval at which to cleanup expired sessions in milliseconds.
expiration: 24 * 60 * 60 * 1000, // The maximum age (in milliseconds) of a valid session.
db: myDatabase
});
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(expressSession({
secret: 'keep it secret, keep it safe.',
store: sequelizeSessionStore,
name: 'session_id',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 7 * 24 * 3600 * 1000,
httpOnly: true
}
}));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, x-access-token");
next();
});
app.use(function(req, res, next) {
application.setRequestSession(req, res);
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
routes(app);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: app.get('env') === 'development' ? err : {}
});
});
http.createServer(app).listen(config.port, function() {
console.log('Listening on port ' + config.port);
});
现在在路由器中,我使用req.session
进行saveUser
调用:
router.post("/saveUser", function(req, res) {
var body = req.body.body;
User.saveUser(body).then(function (data) {
//app.createSession(req);
req.session.user = data;
res.send(200, data);
});
});
对于其他电话,我想检查会话是否存在:
var checkSession = function(req,res,next){
if(req.session.user){
return next();
}
res.status(400).json({
error:"User session authentication error"
});
};
但在这里我有req.session.user
undefined
。为什么?我在这做错了什么?
有什么想法吗?