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 beSELECT * 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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools