Win10 use mysql shell command to operate mysql database

Mysql > install mysql

Link: https://pan.baidu.com/s/1G2RsqXKcRzCbRFc2xfCCng extraction code: 9 m0mCopy the code

Mysql now has its own client connection tool. Here’s how to use the mysql shell.

Install mySql shell when installing mySql. If this option is not selected, install mySql shell later

  1. Open the mysql shell

Open the CMD. Win logo key +R, enter CMD.

  1. Enter mysqlsh in CMD to enter the MySQL shell command line.

  1. Type \connect [email protected] to connect to mysql. Root is the user name, and @ is followed by the DATABASE IP address. Press Enter and enter the password

  1. After successful connection, enter “\ SQL “to enter SQL command mode;

Before entering show datebases; A list of databases is displayed. Use XXX to select a database. After that, you can use all mysql syntax normally.

Such as:

General command

The command Aliases/shortcuts describe
\help \h or ? Print help about MySQL Shell, or search for online help.
\quit \q or \exit Exit the MySQL Shell.
\ In SQL mode, start multi-line mode. The code is cached and executed when empty lines are entered.
\status \s Displays the current MySQL Shell state.
\js Change the execution mode to JavaScript.
\py Change the execution mode to Python.
\sql Change the execution mode to SQL.
\connect \c Connect to the MySQL server.
\reconnect Reconnect to the same MySQL server.
\use \u Specify the schema to use.
\source \. Execute script files using active languages.
\warnings \W Displays any warnings generated by the statement.
\nowarnings \w Do not display any warnings generated by the statement.
\history View and edit command line history.
\rehash Manual update completes the name cache automatically.
\option Query and change MySQL Shell configuration options.
\show Runs the specified report using the provided options and parameters.
\watch Run the specified report with the provided options and parameters and refresh the results periodically.

Mysql > select * from mysqlsh;

  • Linked database:

Connect a root: [email protected]

  • Switch to SQL mode

sql

  • Display database port:

select @@port

MySql Command Line Client

Note: I installed the default database port 3306, password 123456, root user root

2.1 Startup and Exit

1. Enter the MySQL Command Line Client (the DOS interface of MySQL) and enter the installation password. Mysql >

2, exit MySQL: quit or exit

2.2 Database Operations

1. Create a database

Command: create database < database name >;

Mysql > create database jd;Copy the code

2. Display all databases

Command: show databases; (Note: there is an “S” at the end)

mysql> show databases;
Copy the code

Delete the database

Drop database < database name >

Mysql > drop database jd;Copy the code

4. Connect to the database

Use < database name >

For example: if jd database exists, try to access it: mysql> use jd; Screen prompt: Database changedCopy the code

5. View the current database

mysql> select database();
Copy the code

6, the current database contains table information:

mysql> show tables; (Note: there is an "S" at the end)Copy the code

2.3 Table operation. Before operation, connect to a database

1, build table

Command: create table < table name > (< field name > < type > [,.. < field name n > < type n >]);

mysql> create table MyClass(
 id int(4) not null primary key auto_increment,
 name char(20) not null,
 sex int(4) not null,
 degree double(16.2));
Copy the code

2, obtain the table structure

Command: desc table name, or show columns from table name

The following three commands all get the table structure

mysql>DESCRIBE MyClass;
mysql> desc MyClass;
mysql> show columns from MyClass;

Copy the code

3, drop table

Drop table < table name >

Mysql > drop table MyClass;Copy the code

4. Insert data

Command: insert into < table name > [(< fieldname > [,.. < field name n >])] values (values) [, value (n)]

For example, insert two records into table MyClass that represent: Mysql > insert into MyClass values(1,'Tom',1,96),(2,'Joan',1,82);Copy the code

5, query the data in the table

1) Query all rows

Select < field, field… > from < table name > where < expression >

Mysql > select * from MyClass;Copy the code

2) Query the first few rows of data

For example, view the previous data in the table MyClass

Mysql > select * from MyClass order by id limit 0,2; Mysql > select * from MyClass limit 0,2;Copy the code

6. Delete data from the table

Command: delete from table name where expression

Mysql > delete from MyClass where id=1;Copy the code

7, modify table data:

Update table name set name = new value,… Where conditions

mysql> update MyClass set name='Mary' where id=1;

Select * from table where id = 1;

Alter table table name add field type Other;

Mysql > alter table MyClass add passtest int(4) default 2; alter table MyClass add passtest int(4) default 2;Copy the code

Alter table name alter table name

Rename table old table name to new table name;

Mysql > rename table MyClass to YouClass;Copy the code

9. Update the field content

Update set set = replace(replace,' old ',' new ')Copy the code

10. Use a database

use jd;
source D:\vip\vue-jd\jd.sql
Copy the code

Generate an Express framework with express-Generator

3.1 Project generation and start

NPX express --view= EJS -- CSS =less MyApp CD myapp NPM install Nodemon bin/ WWW // Starts and listens in real timeCopy the code

Note: If nodemon is not installed globally, use NPM start or node bin/ WWW to start it

3.2 Adding middleware to facilitate obtaining interface request parameters

Definition:

var url = require('url'); . . // Note that the req.body parameter can be obtained in the post request. Function getParamsMiddle(req, res,next) { if(req.method.toLocaleLowerCase()=='post') { query = req.body; } else { const urlJson = url.parse(req.url,true); query = urlJson.query; } req.query = query; The console. The log (' parameters'); next(); }Copy the code

Use:

File system database FS

Various ways to implement persistence in Node.js

  • File system FS
  • The database
    • Relational database -mysql
    • Document database -mongodb
    • Key value pair database – Redis

4.1 Create fs.js on Routes

var express = require('express'); var fs = require('fs'); var path = require('path'); var router = express.Router(); const {promisify} = require('util'); var base = path.join(__dirname,'.. /data/db.json'); var readFile = promisify(fs.readFile); var writeFile = promisify(fs.writeFile); Router. get('read',function(req, res, next){ readFile(base).then((data)=>{ console.log(data.toString()) res.json(data); }); Get ('/write', function(req, res, next) {var params = req.query; readFile(base).then((data)=>{ console.log(data.toString()); var o1= JSON.parse(data.toString()) var dataTo = {... o1,... params}; return writeFile(base,JSON.stringify(dataTo)); }).then((data)=>{ // res.json(data) res.send('write success'); }); }); module.exports = router;Copy the code

4.2 Importing routes in configuration file app.js

var fsFile = require('./routes/fs'); . . . app.use('/fs', fsFile);Copy the code

4.3 Reading and Writing Files

The previous configuration in 4.1.1 is direct access

http://localhost:3000/fs/read can read data folder db. The json data from http://localhost:3000/fs/write?city=hubei You can write parameters in the form of keys and values to a db.json fileCopy the code

Install and configure MySQL

slightly

Node.js drives the mysql database

6.1 installation mysql2

The node mysql2 module is an extension of the Node mysql module

Yarn add mysql2 or NPM install mysql2Copy the code

If you are using mysql, you may be prompted to upgrade

const mysql = require('mysql');
console.log(mysql)
Copy the code

Use mysql2; Link database and print mysql:

const mysql = require('mysql2');
console.log(mysql)
Copy the code

6.2 mysql Connects to the Database

Mysql can connect to the database through createConnection or createPool

Comparison:

  • The createConnection method creates a connection object

A single connection is blocked. When one query is executed, it cannot execute other queries. As a result, database throughput may be reduced.

  • The createPool method creates a connection pool

Pools manage many connections that are created late. While one connection is busy running queries, other connections can be used to perform subsequent queries. This results in improved application performance because it allows multiple queries to run in parallel.

6.2.1 createConnection Establishing and Closing a Connection (Method 1)

Use the createConnection method to create a connection object representing a connection to the mysql database server

const mysql = require("mysql"); var connection = mysql.createConnection(options); Options: {host:'127.0.0.1', // host IP user: 'root', // database username password: '123456', // change to your password port: '3306', // database port number database: 'jd'Copy the code

(2) Create a connection using the connect method of the object.

Connection.connect (function(err) {console.log(' Database connected! ')});Copy the code

(3) Close the connection: the end method and destory method of the connection object.

Connection. end(function(err) {console.log(' Database closed! ')}); connection.destroy();Copy the code

(4) Complete examples

01-mysql.js

/ / introduction
const mysql = require('mysql2');
// Create a database connection
var connection = mysql.createConnection({
    host: 'localhost'.port: 3306.user: 'root'.password: '123456'.database: 'test'
});

/ / the connection
connection.connect(function (err) {
    if (err) {
        console.log('[query] - :' + err);
        return;
    }
    console.log('Database connection successful! ')});// Query data
connection.query('select * from MyClass'.function (error, results, fields) {
    if (error) throw error;
     console.log(results);
     console.log(fields);
});

// Close the connection
connection.end(function (err) {
    if (err) {
        return;
    }
    console.log('Database has been shut down! ')});Copy the code

Practice some operations on intermediate database tables:


// Add data table
/* create table websites( id init(4) not null primary key auto_increment, name char(20) not null, url char(20) not null, country char(50) not null, ) */

// ****** insert data into the websites table *******
var addSql = 'INSERT INTO websites(name,url,country) VALUES(? ,? ,?) ';
var addSqlParams = ['new'.'https://test.com'.'CN'];
/ / execution
conn.query(addSql, addSqlParams, function (err, res) { 
  if (err) {
    console.log('[INSERT ERROR] - ', err.message);
    return;
  }
  console.log("Result of database increment:");
  console.log(res);
});
// ******end *******

// ****** delete data from websites *******
var delSql = 'DELETE FROM websites where id=1'; 
conn.query(delSql, function (err, res) { 
  if (err) {
    console.log('[DELETE ERROR] - ', err.message);
    return;
  }
  console.log("Database deletion result:");
  console.log(res);
});

// ************ end ****************


// // ****** modify information in the websites table *******
var modSql = 'UPDATE websites SET  url = ? WHERE id = ?';
var modSqlParams = ['https://bang.com'.3];
/ / modify
conn.query(modSql, modSqlParams, function (err, res) {
  if (err) {
    console.log('[UPDATE ERROR] - ', err.message);
    return;
  }
  console.log("Result of database modification:");
  console.log(res);
});
// ************ end ****************

// ****** query information from websites *******
var sql = 'SELECT * FROM websites';
conn.query(sql, function (err, res) {
  if (err) { 
    console.log('[SELECT ERROR] - ', err.message);
    return;
  }
  console.log("Database check result:");
  console.log(res); 
});

// ************ end ****************
Copy the code

Mysql can execute SQL statements in two ways

  • conn.query
  • Conn. execute conn.execute is new to mysql2

Write 01-mysql.js in a different way to take advantage of mysql2’s new features

const mysql = require('mysql2/promise');
    // mysql2 is an extension of mysql
    console.log(mysql);
(async() = > {// // Connection Configuration
    var options= {
        host:'127.0.0.1'.user: 'root'.password: '123456'.// Change it to your password
        port: '3306'.database: 'jd'  // Make sure the database exists
    }

   var conn = await mysql.createConnection(options);
    // mysql executes SQL statements
    // 1. conn.query  
    Conn. execute mysql2 added

   var co01 = await conn.execute('select * from myclass');
    console.log(co01[0])


    // ****** insert data into the websites table *******
    var addSql = 'INSERT INTO websites(name,url,country) VALUES(? ,? ,?) ';
    var addSqlParams = ['nguyen one'.'https://ruan.com'.'CN'];
    / / execution
    var co02= await conn.execute(addSql, addSqlParams);
    console.log('Add data:'+co02[0].affectedRows);

    // ******end *******}) ();Copy the code

6.2.2 createPool Creating a Connection Pool (Method 2)

Connection pooling helps reduce the time it takes to connect to the MySQL server. By reusing previous connections, you can avoid query delays and reduce the overhead of establishing new connections.

In a server application, establishing one or more database connections for every client request received can seriously degrade application performance.

Therefore, a connection pool is typically created and maintained for multiple database connections in a server application, and when connections are no longer needed, they can be cached in the pool and reused when the next client request is received, without having to re-establish the connection.

(1) Create connection pool createPool

var pool = mysql.createPool(optioins);
Copy the code

The Options parameter contains various properties that can be used in the createConnection method, in addition to the following properties: createConnection, waitForConnections, connectionLimit, and getConnection.

Var pool = mysql.createpool ({host:'127.0.0.1', user: 'root', password: '123456', port: '3306', database: 'jd', charset:'utf8', // Encoding should be set (omitted in some cases will be wrong) // The following options are default (omitted if no change is required) acquireTimeout:10000, WaitForConnections: true, // When true, the connection is queued for an available connection. False will immediately throw an error connectionLimit: 10, // The maximum number of connections that can be created at a time queueLimit: 0 // The maximum number of requests in the connection pool, queued from the getConnection method. Setting to 0 will have no limit});Copy the code

(2) Remove the connection from the connection pool

Did not join the initial connection all the connection pool, when need to manipulate the database needs to get connection object Obtain the connection object method (pool. The query () | | pool. The execute () | | pool. The getConnection ()) note: Query () and execute() work the same way (automatically get and release connections)

  • Method 1: Query Connection
// true indicates the condition. A single condition can be directly used as follows. Multiple conditions are in array format. Example: [' name ', 5]
 pool.query("select * from websites ".true.(err,res) = >{
        console.log(res)
})
Copy the code
  • Method 2: getConnection Connection

Pool.getconnection () is recommended to release the connection after obtaining the connection object

    pool.getConnection(function(err, conn) {
    conn.query(/ *... * /);
    // Do not forget to release the connection when you are done! (Return the connection to the connection pool)
    conn.release();
    })
Copy the code

In the callback function, err is the error object and Connection is the fetched connection object. It is recommended that you release the connection after obtaining the connection object operation

(3) When a connection is no longer used, use the Release method of the Connection object to return it to the connection pool.

connection.release();
Copy the code

Release returns the connection to the pool. (4) When a connection is no longer needed and needs to be removed from the pool, use the Destroy method on the Connection object.

connection.destroy(); 
Copy the code

After a connection is removed, the number of connections in the connection pool is reduced by one

(5) When a connection pool is no longer needed, use the end method of the connection pool object to close the connection pool.

pool.end();
Copy the code

(6) Complete example

const mysql = require('mysql2');
var pool = mysql.createPool({
    host: 'localhost'.port: 3306.user: 'root'.password: '123456'.database: 'test'
});
pool.getConnection(function(err, connection) {
    if(err){
        console.log("Failed to establish connection");
    } else {
        console.log("Connection established successfully");
        connection.query('select * from websites'.function(err, rows) {
            if(err) {
                console.log("Query failed");
            } else {
                console.log(rows);
            }
        })
    }
    pool.end();
})
Copy the code

(7) Block query

  • throughconn.pause()Pause the query, useful when processing large amounts of data
  • throughconn.resume()You can continue with the query and continue with the I/O operation after the processing is complete
pool.getConnection((err,conn)=>{ let query = conn.query('select * from websites'); Query. on('error',err=>{// Error handling, an 'end' event is sent after this event}). On ('fields',(fields)=>{// Query row field information console.log('fields'); console.log(fields); }). On ('result',row=>{console.log('row'); console.log(row); conn.pause(); Conn.resume (); }) .on('end',_=>{ conn.release(); // The event will be triggered regardless of success})})Copy the code

Mysql > alter database TRANSACTION

The usage scenario is to execute an SQL group containing multiple SQL statements. On second thought, these SQL statements are either executed at the same time, or not executed at the same time, to ensure data integrity. Simply add begin (or start Transaction) at the beginning of the SQL statement and commit at the end of the SQL statement.

7.1 What is a transaction?

A TRANSACTION is a mysql SQL group with complete logic that contains multiple SQL operations. The SQL must be executed simultaneously for the logic to be complete. Or, rollback the data before the transaction. In the beginning, the teacher used to talk about the situation of bank transfer. That is, when user A transfers money to user B, user A deducts the money, and user B receives the money. If there is a mistake in the link after user A deducts money, user A needs to cancel the deduction, otherwise the data will appear user A deducts money, user B does not receive the account, and the total amount is wrong. At this point, the transaction needs to be added in the transfer operation. Either the transaction is successfully executed at the same time (a deduction, B receipt), or the rollback (A deduction, abnormal error, B account not received, cancel A deduction). This is also the concept of integrity and consistency of features in transactions.

Important: mysql’s MyISam type engine does not support transactions.

7.2 Characteristics of transactions

Atomicity: All operations in a transaction either complete or not complete, and do not end up somewhere in between. If a transaction fails during execution, it will be rolled back to the state before the transaction began, as if the transaction had never been executed.

Consistency: The integrity of the database is not compromised before and after a transaction. This means that the data written must conform to all the preset rules, including the accuracy of the data, the concatenation of the data, and the ability of the subsequent database to do its predetermined work spontaneously.

Isolation: The ability of a database to allow multiple concurrent transactions to read, write, and modify its data at the same time. Isolation prevents data inconsistencies due to cross-execution when multiple transactions are executed concurrently. Transaction isolation can be divided into different levels, including Read uncommitted, Read Committed, Repeatable Read, and Serializable.

Persistence: After a transaction, changes to the data are permanent and will not be lost even if the system fails.

7.3 Transaction Execution Process

Begin (or start transaction) 2. Execute INSERT, UPDATE, delete SQL statements. 3. If the SQL statement fails to be executed, manually rollback. Rollback transactions. Otherwise, commit the transaction.

begin; Update account set money=money+500 WHERE user_id=2; update account set money=money-500 where user_id=3; rollback; // Rollback the transaction. After rollback, no subsequent statements are executed, including commit. commit; // Commit the transactionCopy the code

7.4 Automatic transaction commit

Mysql autocommit indicates whether a transaction is committed automatically. The default value of mysql is automatic commit. That is, after BEGIN starts a transaction, the mysql session window is closed, and the SQL statement is automatically committed without rollback or COMMIT. When autoCOMMIT is disabled (autoCOMMIT =0), the transaction will be committed only after the COMMIT is executed. After the mysql session is closed, the transaction will not be committed.

mysql> show variables like 'autocommit';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| autocommit    | ON    |
+---------------+-------+
1 row in set (0.04 sec)


Copy the code

To view the current session status, on in the value column indicates that the current state is auto commit. To disable autocommit, run set autocommit=0.

Mysql > set autocommit=0;Copy the code

7.5 Example of Transaction Operations

/ * * * 1, using ` ` ` pool. The getConnection () ` ` ` get connection object ` ` ` conn ` ` ` * 2, use ` ` ` conn. BeginTransaction () ` ` ` statement * start transactions 3, use ` ` ` conn. The rollback () ` ` ` transaction rollback * 4, use ` ` ` conn.com MIT () ` ` ` on transaction commit * /
pool.getConnection(function(err, conn) {

    conn.release(); // The test proves that the method can be called here
    conn.beginTransaction(err= >{
        conn.query('update websites set url=? where id=? '['123'.5].(err,res) = >{
            if(err){
                // Use return to prevent code from running down
                return conn.rollback(_= >{
                    // This callback function is executed after the rollback (some additional subsequent operations can be handled here)
                });
            }
            conn.query('update websites set url=? where id=? '['456'.6].(err2,res2) = >{
                if(err2){
                    console.log('err')
                    return conn.rollback();
                } else {
                    console.log(res2);
                }
               
                // Commit after all operations have been performed
                conn.commit(err3= > {
                    if(err3) {
                        return conn.rollback();
                    }
                    console.log('success! '); }); })})})});Copy the code

Sequelize is the ORM framework for connecting to mysql

8.1 What is ORM?

It is a programming technique used to convert data between different types of systems in object-oriented programming languages. In effect, it creates a “virtual object database” that can be used in a programming language.

Used to map objects represented by the object model to the SQL-based relational model database structure.

ORM technology provides a bridge between the object and the database. The object data in the foreground and the relational data in the database are converted to each other through this bridge.

8.2 Installing and Importing Sequelize

yarn add sequelize

8.3 Creating connection Objects and Modularizing them:

dbConn.js

const Sequelize = require('sequelize');

// Database configuration file
var config = {
    host: "localhost".user: "root".password: "123456".database: "jd"
};

var sequelize = new Sequelize(config.database, config.user, config.password, {
    host: config.host,
    dialect: 'mysql'.pool: {
        max: 5.min: 0.idle: 30000}});Copy the code

We created the Sequelize database connection module based on some parameters of the database and referenced it externally.

8.4 Define table structure and write table structure into code:

It is recommended that each table have a document in a separate directory for the project. For example, I usually put it under Models. Here is an example of a todolist table I created.

Define model Fruit and build table

var Sequelize = require('sequelize');
var seq = require('./dbConn.js');

  // define the model and create the table
  const Fruit = seq.define("fruit", {
    name: {
        type: Sequelize.STRING(20),
        allowNull: false
    },
    price: {
        type: Sequelize.FLOAT,
        allowNull: false}}, {timestamps: false
    });

    module.exports = Fruit;
Copy the code

When defining Model with sequelize.define(), pass in the name fruit, and the default table name is FRUITS. The second parameter specifies the column name and data type, or in more detail if it is a primary key. The third parameter is extra configuration. We passed {timestamps: false} to turn off Sequelize’s automatic timestamp addition. All ORM frameworks have a nasty habit of adding smart-alecky “automation” features that can be completely confusing.

8.5 Synchronizing data Table Structures

In the /models directory, create synctable.js with the following code

var todolist = require('./todolist.js'); Todolist.sync ({force: true // force synchronization, delete table first, then create table});Copy the code

Instead of manually synchronizing the data table structure, we simply execute the file when we switch computers to continue the project.

node models/syncTable.js

8.6 Create some Initial Data

Take Watch Fruit as an example:

var Fruit = require('./models/fruit.js'); (async () => {// Add data ret = await Fruit. Create ({name: "gowi ", price: 13.5}) ret = await Fruit. Create ({name:" gowi ", price: 13.5}) ret = await Fruit. Ret2 = await fruit.findall () console.log(ret2); ret2 = await fruit.findall () console.log(ret2); Fruit.findall (). Then (fruits => {const [f1] = fruits; fruits.forEach((option,index)=>{ console.log(option); }) console. The log (` buy 5 kg ${f1. Name} requires RMB ${f1. TotalPrice (5)} `); }); FindOne ({where: {id: 3}}). Then (Fruit => {console.log(fruit.get())); }); }) ()Copy the code

How to use jwt-simple package

Encoding and decoding module

9.1 installation

yarn add jwt-simple

9.2 Generating a Token & Parsing a Token

const tokenExpiresTime = 1000 * 60 * 60 * 24 * 7

/ / the secret key
const jstSecret = 'jstSecret'

// The object to encrypt
const payload = {
    user:'wang'.environment:'web'.expires: Date.now() + tokenExpiresTime
}

/ / encode token is generated
var token = jwt.encode(payload, jstSecret)
console.log('token: ', token)

/ / decoded parsed token
var decoded = jwt.decode(token, jstSecret)
console.log('decoded: ', decoded)

Copy the code

Execution Result:

token: The rm eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9. EyJ1c2VyIjoid2FuZyIsImVudmlyb25tZW50Ijoid2ViIiwiZXhwaXJlcyI6MTUzNTUyMDk1MTcxOX0. 4 P6UeeJ3mQbHfplruH15PvuUxPzFTxAfVnPgA7sgo

decoded: { user: ‘wang’, environment: ‘web’, expires: 1535520951719 }

9.3 token

The entire token is divided into three parts:

  • The head (the header)
  • What’s the payload?
  • Visa (signature)

The token string in the above screenshot is base64 encrypted from these three parts

9.3.1 the Header

{
  'typ': 'JWT',
  'alg': 'HS256'
}
Copy the code

Algorithm is HS256 by default, you can see other options in the source code

/**
 * support algorithm mapping
 */
var algorithmMap = {
  HS256: 'sha256',
  HS384: 'sha384',
  HS512: 'sha512',
  RS256: 'RSA-SHA256'
};
Copy the code

9.3.2 Payload

The core components of the token include: ISS (Issuer): Issuer of the token Sub (Subject): users of the JWT AUD (Audience): token recipients exp(Expiration Time): NBF (Not Before): Token invalid iAT (Issued At): Token issue time JTI (JWT ID): The unique identifier of the JWT is mainly used as a one-time token to avoid replay attacksCopy the code

9.3.3 signature

The signature is created using the encoded header and payload. The signature is obtained by adding the secret key to the specified algorithm. The secret key must be stored on the server. Such as:

HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
Copy the code

9.4 JWT encoding and decoding method

jwt_encode(payload, key, algorithm, options)
jwt_decode(token, key, noVerify, algorithm)
Copy the code

9.5 Instructions

After successfully verifying the information submitted by the user (common user name and password), the server generates the token and returns it to the client based on the public information submitted (user name or ID, sensitive information such as password cannot be used, because the token can also be decrypted on the client side) and the secret key held by the server. The client carries the token in subsequent requests that need to be verified. The server verifies the validity of the user (whether the issuer is the server, whether the token is expired or within the validity period) through the token before each request is processed. After passing the token, the request is processed by other modules.

The general token acquisition validation module is used as middleware

Reference: www.jianshu.com/p/c148a3e9e…