Node.js中的会话 [英] Session in nodejs

查看:79
本文介绍了Node.js中的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉newby问题,但是您能解释一下如何在nodeJS中使用会话。我在互联网上阅读了很多文章,但是我并没有成功实现某些目的(数据正在保存会话,但是每个新的请求会话都是空的),能否从一开始就举例说明如何初始化和使用

sorry for newby question, but can you explain me how to use sessions in nodeJS. I read a lot of articles in internet but I didn't success to implement something for my purpose (data is saving the session, but every new request session is empty), can you give example from the beginning how to initialize and how to use.

目的:当用户登录系统时,我需要为他打开会话,以后他将发送的每个请求我都要检查的是他的会话存在吗?

Purpose: when user do login in the system, I need to open session for him and every request that he will send in the future I need to check is his session exist?

我正在使用Express4.x。我这样做:

I'm using express 4.x. I do it like:

// init session
app.use(cookieParser());
app.use(session({
  secret : "yepiMobileSession",
  resave : true,
  key : "session",
  store: mongooseSession(daoService.mongoose), 
  saveUninitialized : true
}));


// save user to the session
request.session[CONST.SESSION_USER] = user;

// Check login
function checkLogin(id){
        var user = request.session[CONST.SESSION_USER];
        if (user && request.params.clientData && user._id == id){
            return true;
        } else {
            return false;
        }
    }


推荐答案

您可以看看下面的代码。我认为这会对您有所帮助。

You can take a look at the following code. I think this will help you.

var app = require('express')(),
    expressSession = require('express-session'),
    cookieParser = require('cookie-parser');

app.use(cookieParser());
app.use(expressSession({
    secret: 'mYsEcReTkEy',
    resave: true,
    saveUninitialized: true
}));// I haven't used the session store

//setting session

app.post('/login', function(req,res){
  var id=12345;
  req.session.userId = id;
  res.send(200);
});

//getting session

app.get('/hello', function(req,res){
  var id=req.session.userId;
  console.log("Hello",id);
  res.send(200);
});

但是节点服务器和客户端必须位于同一域中。

But node server and client have to be in same domain.

这篇关于Node.js中的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆