简体   繁体   English

Express Session 不会取消设置变量

[英]Express Session doesn't unset variable

I am using Node Express to develop the web application.我正在使用 Node Express 开发 Web 应用程序。 In the new project I faced one simple issue but could not figure out the solution so looking for the help.在新项目中,我遇到了一个简单的问题,但找不到解决方案,因此寻求帮助。

I used express-session to store the session data and stored some data in the session.我使用了 express-session 来存储会话数据,并在会话中存储了一些数据。 After some function I set the session variable to null but still it calls the old session data while calling.在一些函数之后,我将会话变量设置为空,但它仍然在调用时调用旧的会话数据。

Below is my sample code to initialize session.下面是我初始化会话的示例代码。

app.js应用程序.js

app.use(session({
  secret: 'Hhueerutyier',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false }
}));

My Router我的路由器

router.get('/',async function(req,res){
    if(req.session.count && req.session.count != null){
        req.session.count++;
    }else{
        req.session.count = 1;
    }
    let resData = res;
    //JSON.stringify.resData
    console.log("Before Reset =>",req.session.count);
    res.json({
        "data":"I am in check",
        "message" : req.session.msg,
        "count" : req.session.count,
      
    })

   
      req.session.msg = null;
      req.session.count = null; //setting the session varible to null
      console.log("After Reset",req.session.count);
    
})

gives output as给出输出为

在此处输入图片说明

Expected Output
Before Reset => 1
After Reset => null
Before Reset => 1
After Reset => null
Before Reset => 1
After Reset => null

You must edit the session before sending the response!您必须在发送响应之前编辑会话!

const response = {
    "data":"I am in check",
    "message" : req.session.msg,
    "count" : req.session.count,
    
}

/// remove before sending response
req.session.msg = null;
req.session.count = null; 

// Send response
res.json(response)

You can also use delete statement to delete session item:您还可以使用delete语句删除会话项:

delete req.session.msg;
delete req.session.count;

Finally, personally, I like using return statement when sending a response.最后,我个人喜欢在发送响应时使用 return 语句。 It doesn't do anything technically, but it notices me that I shouldn't do anything after it.它在技术上没有做任何事情,但它注意到我不应该在它之后做任何事情。

return res.json(response)

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

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