使用 nodeJS 保持用户登录 [英] Keeping a user logged in with nodeJS

查看:104
本文介绍了使用 nodeJS 保持用户登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 mysql-node 的 NodeJS 登录系统.

I have a login system with my NodeJS using mysql-node.

我遇到的问题是如何让用户保持登录状态,如果他们刷新页面,他们必须再次登录,因为我不知道如何存储会话.

The problem i have how ever is how to keep the user logged in, if they refresh the page they have to login again, because i do not know how to store the session.

我的登录系统是这样的:

My login system is like this:

socket.on('login', function(data,callBack){

    var username = sanitize(data['login']).escape(),
        pass = sanitize(data['password']).escape();

        var query = connection.query('SELECT uid FROM users WHERE name = ? AND pass = ?', [username,pass],
            function(err,results){
                if(err){ 
                    console.log('Oh No! '+err);
                } else if(results.length == 1){
                    //some how set a session here 
                } else if(!results.length) {
                    console.log('No rows found!');
                }
            });
    });

我很难理解如何为每个连接的客户端设置会话.这可以用 NodeJS 实现吗?

I'm having difficulty understanding how i set up a session for each client that connects. Is this possible with NodeJS ?

推荐答案

我认为 Nodejs 的核心中没有任何会话机制.但是,它们有很多库可以让您做到这一点.首先想到的是 Connect 的会话,它是 Nodejs 的中间件.查看这个问题,了解如何使用它的更多详细信息.

I don't think there is any session mechanism within Nodejs' core. However, they are plenty of libraries that would allow you to do it. The first that comes to mind is Connect's session, which is a middleware for Nodejs. Have a look at this question for more details on how to use it.

看看来自dailyjs的本教程将 Express 的会话包含到记事本 web 应用程序中.源代码可在此处获得.(请注意Express 的会话基于 Connect 的会话,并且实际上是相同的).

Have a look at this tutorial from dailyjs which tries to include Express's session into a notepad webapp. The source code is available here. (Note that Express' session is based on Connect's, and is practically the same).

编辑:这是一个更完整的示例 用于节点身份验证,使用猫鼬.然而,它们确实显示了它们的架构,所以我假设您可以轻松地过渡到 MySQL.

EDIT: Here is a more complete example for Node authentication, using mongoose. They do however show their schemas, so I assume you can easily do the transition to MySQL.

这篇关于使用 nodeJS 保持用户登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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