Use session in Express and Socket. IO

Source: Internet
Author: User

Session is required for some authentication in the nodejs project. For example, the demo of the nodejs chat room I wrote is the authentication implemented through session. If a session exists, you can directly log on to the chat room without logging on again.

I also found many session calling methods in the Express framework on the Internet, but I found that not many of them are actually usable. Today, based on the production process of the chat room, I sorted out Express and socket. IO.

Express sessions are implemented through cookies. Two modules in connect are used: parseCookie and MemoryStore. The former is used to parse cookies, and the latter is used to store sesion.

Introduce required module

When using session in the Express framework, you must first introduce the above two modules, for example, the following code:

Var parseCookie = require ('connect '). utils. parseCookie, MemoryStore = require ('connect/middleware/session/memory '); // create a memory store instance var storeMemory = new MemoryStore ({reapInterval: 60000*10 });
App configuration in Express

Add the following configurations to the app:

App. configure (function () {app. use (express. bodyParser (); // parse postapp. use (express. cookieParser (); // parse cookie // set sessionapp. use (express. session ({secret: 'wyq', store: storeMemory }));});
Use session in the request

In the request, we can use request. session to call the session, for example, the following code:

App. get ('/', function (req, res) {// use request. session to determine whether to log on to if (req. session. name & req. session. name! = '') {// You need to determine if you have logged on to res. redirect ('/chat');} else {// read the logon page, requiring logon to var realpath = _ dirname + '/views/' + url.parse('login.html '). pathname; var txt = fs. readFileSync (realpath); res. end (txt );}});
Use session in websocket Communication

In nodejs projects, we often use websockt for communication, so websocket also needs to pass session authentication. In this example, socket. io is used to authenticate the websocket communication session in nodejs. For more information about socket. io, see "using socket. io and node. js to build a websocket application".

The preceding Code introduces the parseCookie used to parse the cookie, so the session is parsed through the cookie. First, we need to process the header file after setting up the socket listener and parse the session in the cookie. For example, the following code:

Var io = sio. listen (app); // sets sessionio. set ('authorization', function (handshakeData, callback) {// obtain the session data handshakeData through the cookie string of the client. cookie = parseCookie (handshakeData. headers. cookie) var connect_sid = handshakeData. cookie ['connect. sid ']; if (connect_sid) {storemory. get (connect_sid, function (error, session) {if (error) {// if we cannot grab a session, turn down the connectioncallback (error. message, false);} else {// save the session data and accept the connectionhandshakeData. session = session; callback (null, true) ;}}) ;}else {callback ('nosession ');}});


In this way, we can use the session in the socket listener, for example, the following code:

Io. sockets. on ('connection', function (socket) {var session = socket. handshake. session; // sessionvar name = session. name; console. log (name); socket. broadcast. emit ('System message', '[' + name + '] is back. Please hurry and talk to him ~~ ');});

For details about the session of middleware in connect and its methods, refer to the official introduction below.

Nodejs chat room

Finally, I attached a chat room of nodejs written in the past few days. Combined with the recently written articles, it seems very easy. The code in it is relatively simple and the comments are clear, it should be helpful for beginners of nodejs:

Download chat rooms based on express + socket. io

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.