NodeJS + Express:跨多个路由共享会话

时间:2018-08-14 23:57:15

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

我有一个带有某些路由的Express Web应用程序。当网络应用与用户交互时,路由需要共享会话。路由是在与app.js分开的js文件中声明的。

在我的app.js

var createError = require('http-errors');
var express = require('express');
var parseurl = require('parseurl')
var session = require('express-session')
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var p_conf = require('./parse_config');

// Declare routes here
var indexRouter = require('./routes/index');    // index route
var usersRouter = require('./routes/users');    // user route
var itemRouter = require('./routes/items');     // item route

var app = express();

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

// set up express-session
var sessionMiddleware = session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true
});

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

// Assign an object to the session
app.use(function (req, res, next) {
  req.session.test = "test";
  next();
});

module.exports = app;

在我的item.js中查找路线:

const path = require('path');
const express = require('express');
const fetch = require('node-fetch');
const router = express.Router();

const p_conf = require('../parse_config');
const db_item = require('../db/db_item');

/* GET route root page. */
router.get('/', function(req, res, next) {
    // Get the object in the session
    console.log(req.session.test);

    db_item.getItems()
    .then(function(result) {
        if (typeof result === "object")
            return res.send(result["results"]);
        else
            return res.send(JSON.stringify({ "Error": String(result) }));       
    })
    .catch((err) => {
        return next(err);
    })
});

module.exports = router;

在app.js中,将在初始化Web应用程序时创建会话并为其分配测试对象。项目路由应该获得相同的会话并检索测试对象。但是,访问路由根时,req.session.test始终为undefined

项目和用户路线如何访问会话并共享会话范围的对象?

1 个答案:

答案 0 :(得分:0)

尝试更改app.js中的路由和会话的声明顺序。另外,在使用会话之前,需要使用sessionMiddlwareapp.use)。

var sessionMiddleware = session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true
});

app.use(sessionMiddleware);
app.use(function (req, res, next) {
  req.session.test = "test";
  next();
});

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