在节点中的不同文件之间使用Node Express会话

时间:2016-12-21 14:56:56

标签: javascript node.js session express

我在 login.js

中的会话中保存了电子邮件
router.get('/signin',function(req,res,next) {
   res.send(req.session.email);//here i can get email from session as well
   console.log("email inside ./signin in login.js "+req.session.email);
});

router.post('/login', function(req, res) {
    req.session.email=req.body.email; //get email from form body
    console.log(req.session.email); // here i can get my email in console 
    res.redirect('/')        //want to redirect to home
});

我想在 index.js

中访问会话中的电子邮件
var session;
router.get('/', function(req, res, next) {
   session=req.session;
    console.log("your mail is"+session.email);
});

这是 app.js config

var

 express = require('express');
var app = express();
    var path = require('path');
    var connection=require('./models/connection');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var session=require('express-session');
    var index = require('./routes/index');
    var users = require('./routes/users');
    var login=require('./routes/login');
    var debug = require("debug");
    var clc = require('cli-color');
    var router=express.Router();
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use(favicon(path.join(__dirname, 'public/images/', 'favicon.gif')));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(cookieParser("secretkey"));
    app.use(express.static(path.join(__dirname, 'public')));
    app.use('/assets', express.static(__dirname + '/assets'));
    app.use(session({secret: 'secretkey',saveUninitialized: true,resave: true}));
    app.get('/login',login);
    app.post('/login',login);
    app.get('/signin',login);
    app.get('/',index);
    module.exports = app;

enter image description here

想要一些像我们可以在php中做的事情

<!-- first page -->
<?php
  session_start(); 
  $_SESSION['myvar'] = 'hello';
?>

<!-- second page -->
<?php
    session_start();
    echo $_SESSION['myvar']; // it will print hello
?>

我尝试了这些以及更多答案,但没有一个能解决我的问题

NodeJS express-session req.session is undefined

req.session is undefined in Node?

How to use req.session data in an other javascript file expressjs

1 个答案:

答案 0 :(得分:1)

所以,我尽可能地尝试了你的代码(从你的代码中复制和粘贴,添加了你没有在这里发布的文件,例如实际开始在端口上监听的server.js文件) ,只需一次更改就可以正常工作。

您的index.js文件实际上并没有将任何内容发送回客户端。请注意您的代码:

var session;
router.get('/', function(req, res, next) {
   session=req.session;
    console.log("your mail is"+session.email);
});

没有调用res.send或res.render,所以它就会挂起来。它与会话值无关,但是,console.log语句仍打印出之前发布的正确电子邮件值。

尝试:

var session;
router.get('/', function(req, res, next) {
   session=req.session;
    console.log("your mail is"+session.email);
   res.send(session.email);
});