Home  >  Article  >  Web Front-end  >  React: ensuring persistent data and seamless sessions

React: ensuring persistent data and seamless sessions

WBOY
WBOYOriginal
2023-09-01 21:49:05810browse

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

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

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:'));

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);

Finally we add a handler for any error events:

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

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");
}
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)});

  });

});

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 }

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

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

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),
    //...

设置 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 })
}))

这里需要注意的一个关键设置是最后一个 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();

这将使用用户输入的值创建 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);

  }
});

现在我们有一些基本的日志记录来查看我们的会话值发生了什么。为了设置它,我们需要像这样配置 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})
});

这两条路由将用作用户名会话变量的获取和设置。现在,通过一些基本的 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?';
  };

});

使用 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:
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