Home  >  Article  >  Web Front-end  >  What is session in node? How to use?

What is session in node? How to use?

不言
不言Original
2018-09-14 14:03:191535browse

The content of this article is about what is session in node? How to use? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Preface

In the previous article, cookies in node were introduced. This article will continue to explain the session.

What is session

Session is just a session, so what is a session?
Session is a concept with a larger granularity than connection. A session may contain multiple connections, and each connection is considered an operation of the session.
When the user jumps between Web pages, the variables stored in the Session object will not be lost, but will persist throughout the user session.
When a user requests a Web page from an application, the Web server will automatically create a Session object if the user does not already have a session. When a session expires or is abandoned, the server terminates the session.

Having said so much, let’s take a look at this product first.

What is session in node? How to use?

It turns out that the session generated by the session middleware is an object, which contains cookie information.

session in node

First, install the express framework, cookieParser middleware, express-session middleware

npm i express --save
npm i cookie-parser --save
npm i express-session --save

By default, the Express session middleware stores session information It is stored in memory and needs to be signed cookie, so when using cookieParser(), you must pass it a secret key. If there is no secret key, it will prompt Error: secret option required for sessions

The code is as follows:

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

var app = express()
app.use(cookieParser())

const hour = 1000 * 60 * 60;
var sessionOpts = {
  // 设置密钥
  secret: 'a cool secret',
  // Forces the session to be saved back to the session store
  resave: true,
  // Forces a session that is "uninitialized" to be saved to the store.
  saveUninitialized: true,
  // 设置会话cookie名, 默认是connect.sid
  key: 'myapp_sid',
  // If secure is set to true, and you access your site over HTTP, the cookie will not be set.
  cookie: { maxAge: hour * 2, secure: false }
}
app.use(session(sessionOpts))

app.use(function(req, res, next) {
  if (req.url === '/favicon.ico') {
    return
  }

  // 同一个浏览器而言,req是同一个
  var sess = req.session;
  console.log(sess)

  if (sess.views) {
    sess.views++;
  } else {
    sess.views = 1;
  }
  res.setHeader('Content-Type', 'text/html');
  res.write('<p>views: ' + sess.views + '</p>');
  res.end();
});

app.listen(4000);

The above code implements a simple page view count Function.
Run the above code, you can open the browser, continuously refresh the page, and observe the sess value printed in the node program.
We found that when the page is refreshed in the same browser, the same session is printed on the console, but the value of views has changed. In other words, multiple http connections correspond to the same session.

session stored in redis

By default, Express session middleware stores session information in memory, but during development and production, it is best to have a persistent and scalable The data stores your session data. The express community has created several session stores that use databases, including MongoDB, Redis, Memcached, PostgreSQL, and others. But low-latency key/value storage is most suitable for this kind of volatile data. Here we first use redis to store session information.

First, install the connect-redis module

npm i connect-redis --save

The code is as follows:

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

var RedisStore = require('connect-redis')(session);

var app = express()
app.use(cookieParser())

var options = {
  host: '127.0.0.1',
  port: 6379,
  db: 1, // Database index to use. Defaults to Redis's default (0).
  prefix: 'ID:' // Key prefix defaulting to "sess:"
  // pass: 'aaa' // Password for Redis authentication
}

const hour = 1000 * 60 * 60;
var sessionOpts = {
  store: new RedisStore(options),
  // 设置密钥
  secret: 'a cool secret',
  // Forces the session to be saved back to the session store
  resave: true,
  // Forces a session that is "uninitialized" to be saved to the store.
  saveUninitialized: true,
  // 设置会话cookie名
  key: 'myapp_sid',
  // If secure is set to true, and you access your site over HTTP, the cookie will not be set.
  cookie: { maxAge: hour * 8, secure: false }
}
app.use(session(sessionOpts)) // 如果没有secret,会提醒 Error: secret option required for sessions

app.use(function(req, res, next) {
  if (req.url === '/favicon.ico') {
    return
  }

  var sess = req.session;
  var id = req.sessionID; // session ID, 只读
  console.log(sess, id);

  if (sess.views) {
    sess.views++; // 如果放在res.end()后,不会自增
    res.setHeader('Content-Type', 'text/html');
    res.write('<p>views: ' + sess.views + '</p>');
    res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
    res.end();
  } else {
    sess.views = 1;
    res.end('welcome to the session demo. refresh!');
  }
});

app.listen(4000);

In the above program, the session information is stored in the db1 database of redis. After running, refresh Browser, the information in the database is as follows:

What is session in node? How to use?

session is stored in mongoDb

First, you must install the connect-mongo module

npm i connect-mongo --save

The code is as follows:

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

var MongoStore = require('connect-mongo')(session);
const hour = 1000 * 60 * 60

var app = express()
app.use(cookieParser())
app.use(session({
  secret: 'a cool secret',
  key: 'mongo_sid',
  cookie: { maxAge: hour * 8, secure: false },
  resave: true,
  saveUninitialized: true,
  store: new MongoStore({
    url: 'mongodb://@localhost:27017/demodb'
  })
}));

app.use(function(req, res, next) {
  if (req.url === '/favicon.ico') {
    return
  }

  var sess = req.session;
  var id = req.sessionID; // session ID, 只读
  console.log(sess, id);

  if (sess.views) {
    sess.views++;
  } else {
    sess.views = 1;
  }

  res.setHeader('Content-Type', 'text/html');
  res.write('<p>views: ' + sess.views + '</p>');
  res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
  res.write('<p>httpOnly: ' + sess.cookie.httpOnly + '</p>');
  res.write('<p>path: ' + sess.cookie.path + '</p>');
  res.write('<p>secure: ' + sess.cookie.secure + '</p>');
  res.end();
});

app.listen(4000);

After running, refresh the browser page and find that the following session information has been stored in the sessions collection in the demodb database.

What is session in node? How to use?

Some people may ask: The result is seen, but what happened in the process?
In fact, when the browser initiates the first request, the session middleware will generate a session object (which contains cookie information). This session object will be stored in the mongoDb database. At the same time, the request returns , the browser client will automatically save the cookie in this session object. Note that the browser saves the cookie, not the session object.
This cookie has an expiration time, for example, the setting in the above code is 8 hours. In other words, this cookie will automatically disappear in the browser after 8 hours.

Related recommendations:

What is Session

How to use socket.io_node.js in node’s express

The above is the detailed content of What is session in node? How to use?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn