在中间件中未定义但在控制器中定义的快速会话

时间:2019-05-20 13:58:42

标签: javascript node.js express backend express-session

我的快速会话出现问题,该会话在中间件中未定义但在控制器中定义。

这是将会话放入控制器时的代码

exports.login = (req, res, next) => {
    User.find({username: req.body.username}, (err, data) => {
        if (data.length === 1) {
            const password = data[0]['password']
            bcrypt.compare(req.body.password, password, (err, check) => {
                if (err) console.error(err)
                if (check) {
                    req.session.username = data[0]['username']
                    req.session.userid = data[0]['id']
                    console.log("session when logged in => " + req.session.username) //the session is defined
                    res.redirect('/dashboard')
                } else {
                    res.status(304).send('password salah')
                }
            });
        } else {
            res.status(304).send('username / password tidak tersedia')
        }
    })
}

但是当我在中间件中检查会话

const usermiddleware = (req, res, next) => {
    console.log(req.session.username + " => session in middleware") //undefined
    if (req.session.username) {
        next()
    } else {
        res.redirect('/') //runs here
    }
}

这是我的app.js

let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
let bodyparser = require('body-parser');
let mongoose = require('mongoose');
let session = require('express-session')
var socket_io = require('socket.io');
let app = express();
let io = socket_io();
app.io = io;


io.on("connection", socket => {
    console.log("A user connected");
});
app.use((req, res, next) => {
    req.io = io;
    next()
})

app.use(session({
    secret: 'asd123',
    saveUninitialized: true,
    resave: true,
    cookie: {
        secure: true
    } 
}))
app.use((req, res, next) => {
    app.locals.username = req.session.username || ""
    app.locals.userid = req.session.userid || ""
    next()
})

app.use((req, res, next) => {
    mongoose.connect('mongodb://localhost/inventory', {
        useNewUrlParser: true,
        keepAlive: true,
        keepAliveInitialDelay: 300000
    });
    const db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', () => {
        req.db = mongoose.connection;
        next()
    });
})

let indexRouter = require('./routes/index');
let usersRouter = require('./routes/users');


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true}));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use((req, res, next) => {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

这是我的全索引路由器

let express = require('express');
let router = express.Router();
const usermiddleware = (req, res, next) => {
    console.log(req.session.username + " => session middleware")
    if (req.session.username) {
        next()
    } else {
        res.redirect('/')
    }
}

const auth = require('../controller/auth');
const page = require('../controller/page');

router.get('/', page.index);
router.post('/register', auth.register);
router.post('/login', auth.login);
router.get('/logout', auth.logout)

router.get('/dashboard', usermiddleware, page.dashboard);
router.get('/admin', usermiddleware, usermiddleware, page.admin);

module.exports = router;

注意:我正在将Express Session与带有套接字io和monggose的express生成器一起使用

1 个答案:

答案 0 :(得分:0)

只需在cookie: {secure : false }中设置app.use(session({})),因为我正在cookie:true用于https协议的本地主机中运行

希望这会有所帮助!