让req.session成为全球性的(Node JS)

时间:2017-03-23 07:16:08

标签: javascript node.js

如何在app.js文件中使req.session.sess1全局隐藏?谢谢。当我打算在另一个请求中使用它时,req.session.sess1仍未定义。我在函数内部进行了一个会话。我还可以访问该功能之外的会话内容吗?

//Loading session related npm
var express = require('express');
var session = require('express-session');

// Put all npm in app
var app = express();

// Setup session middleware
app.use(session({ secret: 'keyboard cat', key: 'sid', resave:true,      saveUninitialized:true }));

// Example use of session
app.get('/createsession', function (req, res) {
var sessioncontent1 = "session1";
var sessioncontent2 = "session2";
    //now the req here is not belongs to the function above
    req.session.sess_1 = sessioncontent1;
    console.log(req.session.sess_1);
});

// You will be able to get the session content in another variable
app.get('/usepastsession', function (req, res) {
    // the session is said to be undefined, how to make it become global?
    if (req.session.sess_1) {
        console.log(req.session.sess_1);
    }
});

app.get('/', function (req, res) {
    res.end('Hello World');
});

app.get('/killsession', function (req, res) {
    delete req.session.sess_1;
});

app.listen(1337);

0 个答案:

没有答案