1. Install jsonwebtoken

    npm install jsonwebtoken --save

  2. Add token.js to generate and validate tokens

    const jwt = require("jsonwebtoken")
    const signkey = 'mes_qdhd_mobile_xhykjyxgs'
    
    exports.setToken = (username) = > {
        return new Promise((resolve, reject) = > {
            // The first parameter received by sing is an object (it can be customized). If the first parameter is JWT malformed, an error is reported
            const token = jwt.sign({
                username
            }, signkey, { expiresIn: '1h'}); resolve(token); })}exports.verToken = (token) = > {
        return new Promise((resolve, reject) = > {
            jwt.verify(token, signkey, (err, result) = > {
            Token.split ('.')[1]; token.split('.')[1]
            // var parts = jwtString.split('.');
    
            // if (parts.length ! = = 3) {
            // return done(new JsonWebTokenError('jwt malformed'));
            // }
                if (err) {
                    console.log(err);
                    reject(err)
                } else {
                    console.log(result);
                    resolve(result)
                }
            })
        })
    }
    Copy the code
  3. Add configuration in app.js

    const token = require("./token")
    
    app.use(function(req, res, next) = >{
        
        const URL = req.url
    
        if (URL === '/login') {
        // No verification is required for the login interface
            return next()
        }
        
        // Obtain the token value
        const authorization = req.headers['authorization'];
    
        if (authorization === "undefined") {
            return res.status(401).send('Unauthorized')}else {
            / / authentication token
            token.verToken(authorization).then((data) = > {
                req.data = data;
                return next();
            }).catch((error) = > {
                return res.status(401).send('Unauthorized'); })}})Copy the code
  4. Set the token value after login

    const token = require("./token")
    
    app.use("/login".(req, res) = > {
    // Logon logic
        token.setToken(req.body.username).then(token= > {
            res.status(200).send({
                token,
            })
        })
    })
    Copy the code