Table of Contents
Session?
Document Storage
Add sessions to our app
持久登录
结论
Home Web Front-end JS Tutorial React: ensuring persistent data and seamless sessions

React: ensuring persistent data and seamless sessions

Sep 01, 2023 pm 09:49 PM

React: ensuring persistent data and seamless sessions

Having a "remember me" feature is a very useful feature and is relatively easy to implement using React and Express. Continuing with our previous part of setting up a WebRTC chat application, we will now add Mongo-backed persistent sessions and a database-backed list of online users for good measure.

Session?

If you haven't used sessions before, in short, they are very similar to cookies in that sessions allow you to track active users of your application in real time. Sessions actually work via a session cookie, which is sent in the request/response headers from your application.

So cookies and sessions are inherently intertwined. Why do we need a session if we already have cookies? Sessions also provide you with the ability to define the backend storage used by the server portion of your application. This means that the information can be retrieved from the database whenever your app needs it.

So, in our real-life example of a chat application, we can now store the user's username - and if we reconfigure our application a bit, also insert the entire chat history into the database for logging.

In the next example, we will use a Mongo database for persistent backend storage. This is one of several options available for session storage, another option I highly recommend for large-scale production setups with multiple web servers is memcache.

Document Storage

Mongo is a NoSQL document storage engine, not a relational data store like the popular MySQL. If you've worked with MySQL or similar databases before and need to get up to speed on Mongo, NoSQL is really easy to get started with - it won't take you long. The biggest differences you should know are as follows:

  • As the name suggests, NoSQL does not use SQL to execute queries. Instead, the data is abstracted through method calls; for example db.collectionName.find() would be SELECT * FROM table.
  • The terminology is different: in MySQL we have tables, rows and columns, while in Mongo we have collections, documents and keys.
  • The data is structured, the same as JSON objects.

If you don't have Mongo yet, install it through your package manager. For example, in Linux-based distributions:

$ sudo apt-get install mongodb
Copy after login

After installing Mongo, we can easily add Mongo support to our chat application using the mongoose module provided by npm. Install mongoose using the following command:

$ npm install mongoose --save
Copy after login

Now let's add some Mongo to our application. Launch the code editor, then open app.js and set the top of the script as follows.

//Configure our Services
var PeerServer = require('peer').PeerServer,
    express = require('express'),
    mongoose = require('mongoose'),
    assert = require('assert'),
    events = require('./src/events.js'),
    app = express(),
    port = process.env.PORT || 3001;

//Connect to the database
mongoose.connect('mongodb://localhost:27017/chat');
var db = mongoose.connection;

mongoose.set('debug', true);

db.on('error', console.error.bind(console, '# Mongo DB: connection error:'));
Copy after login

We include mongoose in require('mongoose') and then pass mongoose.connect('mongodb://localhost:27017/chat') ;.

/chat Define the name of the database we want to connect to.

Next, for development purposes, I recommend that we set debugging to on.

mongoose.set('debug', true);
Copy after login

Finally we add a handler for any error events:

db.on('error', console.error.bind(console, '# Mongo DB: connection error:'));
Copy after login

Next, you can add a check on the connection using the following code:

db.once('open', function (callback) {
  console.log("# Mongo DB:  Connected to server");
}
Copy after login
The way

mongoose is used is that once the db instance receives the open event, we move into executing our mongo connection. Therefore, we need to wrap our existing code into this new mongo connection to use it.

Below is the complete code listing that adds mongoose and inserts and deletes rows when the user is online and offline.


//Configure our Services
var PeerServer = require('peer').PeerServer,
    express = require('express'),
    mongoose = require('mongoose'),
    assert = require('assert'),
    events = require('./src/events.js'),
    app = express(),
    port = process.env.PORT || 3001;

//Tell express to use the 'src' directory
app.use(express.static(__dirname + '/src'));

//Connect to the database
mongoose.connect('mongodb://localhost:27017/chat');
var db = mongoose.connection;

mongoose.set('debug', true);

db.on('error', console.error.bind(console, '# Mongo DB: connection error:'));

db.once('open', function (callback) {

  console.log("# Mongo DB:  Connected to server");

  //Setup our User Schema
  var usersSchema = mongoose.Schema({username: String});
  var User = mongoose.model('User', usersSchema);

  //Configure the http server and PeerJS Server
  var expressServer = app.listen(port);
  var io = require('socket.io').listen(expressServer);
  var peer = new PeerServer({ port: 9000, path: '/chat' });

  //Print some console output
  console.log('#### -- Server Running -- ####');
  console.log('# Express:   Listening on port', port);

  peer.on('connection', function (id) {
    io.emit(events.CONNECT, id);
    console.log('# Connected: ', id);

    //Store Peer in database
    var user = new User({ username: id });
    user.save(function (err, user) {
      if (err) return console.error(err);
      console.log('# User '+ id + ' saved to database');
    });

  });

  peer.on('disconnect', function (id) {
    io.emit(events.DISCONNECT, id);
    console.log('# Disconnected: ', id);

    //Remove Peer from database
    User.remove({username: id}, function(err){ if(err) return console.error(err)});

  });

});
Copy after login

To see this in effect, let's launch the chat application. Just run npm start to start.

Now connects to the chat normally in the browser (default is http://localhost:3001).

After connecting to the chat, open mongo chat in a new terminal window and enter the mongo cli.

$ mongo chat
MongoDB shell version: 2.0.6
connecting to: chat
> db.users.find()
{ "username" : "CameronLovesPigs", "_id" : ObjectId("5636e9d7bd4533d610040730"), "__v" : 0 }
Copy after login

Here your mongo document records are stored, now you can check how many users are online() at any time by running db.users.count in the mongo prompt.

> db.users.count()
3
Copy after login

Add sessions to our app

Since we are using Express to build our application, this part is very simple and only requires installing a few modules from npm to get started.

Get the express-session and connect-mongo packages from npm:

$ npm install express-session connect-mongo cookie-parser --save
Copy after login

Now include them at the top of app.js:

var PeerServer = require('peer').PeerServer,
    cookieParser = require('cookie-parser'),
    express = require('express'),
    session = require('express-session'),
    mongoose = require('mongoose'),
    MongoStore = require('connect-mongo')(session),
    //...
Copy after login

设置 mongoose.connect 后,您可以使用 Express 配置会话。将您的代码更改为以下内容;您可以指定自己的 secret 字符串。

//Connect to the database
mongoose.connect('mongodb://localhost:27017/chat');
var db = mongoose.connection;

mongoose.set('debug', true);

db.on('error', console.error.bind(console, '# Mongo DB: connection error:'));

app.use(cookieParser());
app.use(session({
  secret: 'supersecretstring12345!',
  saveUninitialized: true,
  resave: true,
  store: new MongoStore({ mongooseConnection: db })
}))
Copy after login

这里需要注意的一个关键设置是最后一个 app.use 中的 saveUninitialized: true 。这将确保保存会话。

我们使用 store 属性指定位置,该属性设置为 MongoStore 实例,通过 mongooseConnection 和我们的 db 对象。

为了存储到会话中,我们需要使用express来处理请求,因为我们需要访问请求值,例如:

//Start persistent session for user
app.use(function(req, res, next) {
	req.session.username = id;
	req.session.save();
Copy after login

这将使用用户输入的值创建 req.session.username 变量并保存以供稍后使用。

接下来,我们可以使用客户端代码检查此值,并在用户刷新时自动登录,这样他们就永远不会退出聊天并自动以其选择的用户名登录。

还值得注意的是,因为我们有数据库支持的会话,所以如果开发人员更改应用程序和后端重新加载,登录到其客户端的用户将保持登录状态,因为会话存储是现在执着。这是一个很棒的功能,可以让您的用户在开发过程中或在与不稳定的客户端断开连接时始终保持登录状态。

持久登录

现在我们已经设置了会话 cookie 部分,接下来让我们将持久登录添加到我们的前端代码中。

到目前为止,我们只是使用了 Express 为 SPA 应用程序提供的默认路由,并没有为 Express 定义任何路由处理。正如我之前提到的,要访问会话,您将需要 Express 的请求/响应变量。

首先,我们需要一个路由,以便我们可以访问 Express 提供的 request 对象并显示它以进行调试。在 /app.js 中的 Express 配置内,在会话设置之后,在文件顶部附近添加以下内容:

app.use(session({
  secret: 'supersecretstring12345!',
  saveUninitialized: true,
  resave: true,
  store: new MongoStore({ mongooseConnection: db })
}))

app.get('/', function (req, res) {
  res.sendFile(__dirname +'/src/index.html');
  if(req.session.username == undefined){
    console.log("# Username not set in session yet");
  } else {
    console.log("# Username from session: "+ req.session.username);

  }
});
Copy after login

现在我们有一些基本的日志记录来查看我们的会话值发生了什么。为了设置它,我们需要像这样配置 getter 和 setter 路由:

//Save the username when the user posts the set username form
app.post('/username', function(req, res){
  console.log("# Username set to "+ req.body.username);
  req.session.username = req.body.username;
  req.session.save();
  console.log("# Session value set "+ req.session.username);
  res.end();
});

//Return the session value when the client checks
app.get('/username', function(req,res){
  console.log("# Client Username check "+ req.session.username);
  res.json({username: req.session.username})
});
Copy after login

这两条路由将用作用户名会话变量的获取和设置。现在,通过一些基本的 JavaScript,我们可以为我们的应用程序实现自动登录。打开src/App.js,修改如下:

/* global EventEmitter, events, io, Peer */
/** @jsx React.DOM */

$(function () {
  'use strict';

  // Check for session value
  $(document).ready(function(){
    $.ajax({
          url: '/username'
    }).done(function (data) {
      console.log("data loaded: " + data.username);
      if(data.username)
        initChat($('#container')[0], data.username);
    });
  });

  // Set the session
  $('#connect-btn').click(function(){
    var data = JSON.stringify({username: $('#username-input').val()});
    $.ajax({ url: '/username',
              method: "POST",
              data: data,
              contentType: 'application/json',
              dataType: 'json'
            });
  });

  // Initialize the chat
  $('#connect-btn').click(function () {
    initChat($('#container')[0],
      $('#username-input').val());
  });

  function initChat(container, username) {
    var proxy = new ChatServer();
    React.renderComponent(, container);
  }

  window.onbeforeunload = function () {
    return 'Are you sure you want to leave the chat?';
  };

});
Copy after login

使用 jQuery 的 $.ajax 工具,我们创建一个请求,以在 文档 可用时检查会话变量的值。如果设置了,我们就会使用存储的值初始化我们的 React 组件,从而为我们的用户提供自动登录功能。

使用 npm start 再次启动聊天,并在浏览器中查看会话是否正常工作。

结论

现在您已经看到将 Mongoose 与 Express 结合使用并设置 Express 会话是多么容易。使用 React 作为链接到数据库支持元素的视图控制器来进一步开发应用程序将创建一些重要的应用程序。

如果您想进一步了解 React 并了解组件如何在 React 框架内部相互通信,官方文档中的这份指南非常有用。

The above is the detailed content of React: ensuring persistent data and seamless sessions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles