A number of third-party modules need to be introduced

const express = require('express')
const router = express.Router()
const db = require('.. /db')
const md5 = require('md5')
const jwt = require('jsonwebtoken')

router.use((req, res, next) = > {
    let {
        username,
        password
    } = req.body
    if (!/ ^ [a zA - Z] [0-9 a zA - Z] {1, 9} $/.test(username)) {
        next('Username enter 2-10 characters, must start with a letter')}else if (!/ ^ \ S $/ 6, 12 {}.test(password)) {
        next('Password can only be 6-12 digits')}else {
        next()
    }
})

router.post('/reguser'.(req, res) = > {
    let {
        username,
        password
    } = req.body

    password = md5(password)

    db(`select * from user where username='${username}'`.(err, result) = > {
        if (err) throw err
        if (result.length > 0) {
            res.send({
                status: 1.message: 'User already exists'})}else {
            db(`insert into user set username='${username}',password='${password}'`.(e, r) = > {
                if (e) throw e
                res.send({
                    status: 0.message: 'Registration successful'.data: r
                })
            })
        }
    })
})

router.post('/login'.(req, res) = > {
    let {
        username,
        password
    } = req.body

    password = md5(password)

    db(`select * from user where username='${username}' and password='${password}'`.(err, result) = > {
        if (err) throw err
        if (result.length > 0) {
            let token = jwt.sign({
                id: result[0].id
            }, 'qwewerqwee', {
                expiresIn: '2h'
            })
            res.send({
                status: 0.message: 'Successful landing'.token: 'Bearer ' + token
            })
        } else {
            res.send({
                status: 1.message: 'Login failed'
            })
        }
    })
})

router.use((err, req, res, result) = > {
    res.send({
        status: 1.message: err
    })
})


module.exports = router
Copy the code