Build projects using Express

  1. Install express-Generator. Global installation is recommended

    npm install -g express-generator
    Copy the code
  2. Create projects using express-Generator tools

    Express Project nameCopy the code
  3. Allow projects to start

    CD project NPM install Go to local NPM start to start the project http://127.0.0.1:3000 http://localhost:3000Copy the code

Change your own app.js code, import a new interface, create api.js.

Identity authentication process

1. The user enters the login information and sends the login request to the backend.

2. The server verifies the login information. If the login is successful, the service adz generates a token (a token used to save user information).

3. Return the generated token to the front-end, which stores the token locally through localStorage.

4. In all subsequent clearings, the front chi will carry the token and send it to the background;

5. The back-end verifies whether the token exists. If yes, the back-end verifies whether the token is valid and expired.

6. If the verification fails, the backend presses 401 to report an error to the front-end.

7. If the authentication is successful, decode the token and return the user information saved in the token to the front end.

8. If the user logs out, delete the token from the local storage.

Front end and back end separation steps

1. The first installation

npm i jsonwebtoken

Api.js is equivalent to setting the username and password in post, then retrieving the key signature parsed in POST, and typing GET in token to judge. Then go to Add.js for judgment and jump.

Var JWT =require(” jsonwebToken “)

3. Generate token value (key + account + password)

Const token=jwt.sign({data: 'user information, password account'}, 'key signature ', {expiresIn: expiration time, general h});Copy the code
router.post('/1ogin', function (req, res, next) { // 1. Const user = req.body; If (user.username! . = 'red' | | user password! = 123456) {// If not, send res.send({status: 0, MSG: "account or password error"})} // 2. Const Token = jwt.sign(user, 'kongbai', {expiresIn: '24h'}); Res. send({status: 1, MSG: "login succeeded ", data: {Token: Token}})});Copy the code

Design successful login interface, token judgment

Router. Get ('/menus', (req,res,next)=>{// After the request interface, must be in the state of res.send({MSG: "helloworld" }) })Copy the code

The GET interface must carry the token value after successful login

NPM install express-jwt –save

var expressJwt = require(“express-jwt”);

Use ({secret: 'kuaixiang1991', algorithms: ['HS256'] // encryption algorithm}).unless({path: ['/', '/ API /login'] })) app.use(function(err, req, res, Next) {if (err. Name === 'UnauthorizedError') {console.error(req.path + ', invalid token'); Res. json({MSG: 'token expired or invalid, please login again ', status: 401}) res. Redirect (302, "http://127.0.0.1:5500/index.html") return} next ()})Copy the code

Then enter the account password on the login page to obtain the token. If you log in again after the expiration date, the login success page will be displayed if the login is correct.