简体   繁体   English

NodeJS变量会话未定义

[英]NodeJS Variable Sessions undefined

I'm trying to set up a session variable in my NodeJS application that should store the current user. 我正在尝试在应该存储当前用户的NodeJS应用程序中设置会话变量。

Unfortunately, I always get the following error : 不幸的是,我总是得到以下错误:

TypeError: Cannot set property 'user' of undefined TypeError:无法设置未定义的属性“用户”

One of my requisite is that I should not use a database to store the sessions, as it is a student project and I must respect the architecture asked. 我的必要条件之一是,我不应该使用数据库来存储会话,因为这是一个学生项目,因此我必须尊重所要求的体系结构。

Here is the function I use to login my user : 这是我用来登录用户的功能:

this.POSTLogin =function POSTLogin(LoginInformations,res,req){
    //prepare request
    var args = {
        data:{username:LoginInformations.username,password:LoginInformations.password},
        headers:{"Content-Type":"application/json"}
    };
    //check if credentials are valid
    client.post(this.restBaseUrl+"users/login",args,function(data,response){
        //logs for debug purpose
        console.log(data);
        console.log(response);
        //if there is a user
        if(response.statusCode == 200){
            var usr = new User();
            usr.email       = data.email       ;
            usr.facebookData= data.facebookData;
            usr.firstName   = data.firstName   ;
            usr.id          = data.id          ;
            usr.lastName    = data.lastName    ;
            usr.restToken   = data.restToken   ;
            usr.role        = data.role        ;
            usr.sessions    = data.sessions    ;
            var Rest = new RestService();
            //this line doesn't work
            req.session.user = usr;
            //redirect to his personal page with data
            Rest.GETPersonalStats(usr,res);

        }else{
            //is there is no user with those credentials, send it to login page again
            res.redirect('/users');
        }
    });
};

When I'm not trying to save the data into a session, everything works as expected. 当我不尝试将数据保存到会话中时,一切都会按预期进行。

At the start of this file, I have : 在此文件的开头,我有:

var session = require('client-sessions');
var express = require('express');
var app = express();
app.use(session({
    cookieName: 'session',
    secret: 'someRandomString',
    duration: 30 * 60 * 1000,
    activeDuration: 5 * 60 * 1000
}));

I did add "client-sessions" into my package.json file. 我确实在我的package.json文件中添加了“客户端会话”。 I followed information based on this article . 我根据这篇文章了解了信息。

EDIT: Based on @Shoyeb Memon's answer, I changed to use cookie-session. 编辑:基于@Shoyeb Memon的答案,我更改为使用cookie会话。 I now have this in my declaration : 我现在在声明中有此内容:

var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var app = express();
app.use(cookieParser('akey'));
app.use(cookieSession({
    name:'session',
    keys:['akey'],
    maxAge: 24 * 60 * 60 * 1000
}));

but the error didn't change at all... I used this to implement the sessions. 但是错误根本没有改变...我用来实现会话。

EDIT 2: When I changed my code the first time, I wanted to do it without copy-paste, and I followed instructions online. 编辑2:当我第一次更改代码时,我想在没有复制粘贴的情况下进行操作,并且我遵循了在线说明。 But I did try copy-pasting all, I removed the "store" and it seems to work fine now. 但是我确实尝试了全部复制粘贴,删除了“存储”,现在看来工作正常。

I will give you an example of it from my previous work which might be helpful to you 我将通过以前的工作为您提供一个示例,这可能会对您有所帮助

I have used express-session 我用过快递会议

const session = require('express-session');
const bodyParser = require('bosy-parser');

//Set Cookie
app.use(session(
{
 name: 'myName',
 secret: '#@$#!ng',
 resave: true,
 saveUninitialized: true,
 overwrite: true,
 unset: 'destroy',
 rolling: true,
 "cookie": {
   maxAge: 1000 * 60 * 15000000
  },
 store: new (require('express-sessions'))({
    storage: 'mongodb',
    instance: mongoose, // optional
    host: 'localhost', // optional
    port: 27017, // optional
    db: 'codepost', // optional
    collection: 'mysessions', // optional
    expire: 1000 * 60 * 15000000
   })
 }
));

I have set the cookie and stored my sessions in my database 我已经设置了cookie并将会话存储在数据库中

Using session in one of my api: 在我的API之一中使用会话:

const express = require('express');
const app = express();
const router = express.Router();

router.post("/validate", function(req,res){

  req.session.phoneNumber = req.body.phoneNumber;//storing value into 
                                                // session

  let userPhoneNumber = req.session.phoneNumber;//assigning to a var
  console.log(userPhoneNumber);

 }

Use can use the session to store the data which you have got from a text input. Use可以使用该会话来存储您从文本输入中获取的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM