Install express – JWT

npm install express-jwt
npm install jsonwebtoken
Copy the code

Configuration JWT (index. Js)

const jwt = require('express-jwt'); // app.use(jwt().unless()); // unless() completes authentication app.use(JWT ({secret: ['HS256'] // Mandatory, encryption algorithm}). Unless ({path: ['/API/login ', '/ API/reguser'] / / in addition to these two interfaces, other all need certification}));Copy the code

To generate the token (login. Js)

 let token =
        "Bearer " +
        jwt.sign({ id: result[0].id }, "fdsggs", { expiresIn: "2h" });
Copy the code

Login interface (login.js)

router.post("/login", function (req, res) { let { username, password } = req.body; password = md5(password); let sql = `select * from user where username='${username}' and password='${password}'`; db(sql, (err, result) => { if (err) throw err; // console.log(result); if (result.length > 0) { let token = "Bearer " + jwt.sign({ id: result[0].id }, "fdsggs", { expiresIn: "2h" }); Res. send({status: 0, message: "login succeeded ", token}); } else {res.send({status: 1, message: "account or password error"}); }}); // res.send("POST request to the homepage"); });Copy the code

Vue front-end route guard restrictions

// JWT user permission check, Determine whether the TOKEN is router in localStorage. BeforeEach (({name}, from, GetItem (' Token ')) {// If (name === 'login') {next('/'); } else { next(); } } else { router.push('/login') } });Copy the code

Method of Carrying Token by Headers in VUE Component (1)

var that=this; / / for this course list. Axios ({method: "get", url: "http://localhost:3000/api/v1/courses", headers:{ authorization:'Bearer '+window.localStorage.getItem('token') } }).then(result=>{ if(result.data.length>0){ that.courses=result.data; }})Copy the code

(2) Set the AXIos interceptor

Add the following code to SRC /main.js for each backend request that carries the header: / / HTTP request interceptor optional axios. Interceptors. Request. Use (config = > {the if (localStorage. Token) {/ / judge the existence of a token, if any, Is each HTTP headers and token config. Headers. Authorization = ` Bearer ${localStorage. Token} `; } return config; }, err => { return Promise.reject(err); }); axios.interceptors.response.use( response => { return response; }, error => {if (error.response.status === 401) {// Output authorization failure error message} else {// Output other error message} return promise.reject (error); });Copy the code