express project creation, connection mysql, jwt verification

 

The code has been uploaded to Baidu network disk

Link: https://pan.baidu.com/s/1m4wfWmeFPoNVExSE5eVG4w
Extraction code: 8888 After 
copying this content, open Baidu Netdisk  mobile phone App, the operation is more convenient

I won’t introduce express and node because I don’t know how to introduce it. Don’t ask, just don’t know.

1. Create a project and do it yourself with Taobao mirroring

mkdir dh-express
cd dh-express
cnpm init -y

2. Install the following things by yourself

    "body-parser": "^1.19.0",
    "boom": "^7.3.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "express-jwt": "^5.3.1",
    "jsonwebtoken": "^8.5.1",
    "md5": "^2.2.1",
    "mysql": "^2.18.1",
    "nodemon": "^2.0.3"

3. Create app.js

const express = require('express')
const router = require('./router')
const bodyParser = require('body-parser')
const cors = require('cors')
// 创建 express 应用
const app = express()
app.use(cors()) // 跨域用的
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/', router)
// 使 express 监听 9000 端口号发起的 http 请求
const server = app.listen(9000, function() {
  const { address, port } = server.address()
  console.log('Http Server is running on http://localhost:9000', address, port)
})

4. The following concepts express basic concepts by yourself: middleware, routing, exception handling

5、package.json

{
  "name": "express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "boom": "^7.3.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "express-jwt": "^5.3.1",
    "jsonwebtoken": "^8.5.1",
    "md5": "^2.2.1",
    "mysql": "^2.18.1",
    "nodemon": "^2.0.3"
  }
}

6, nodemon.json Its function is to monitor the changes of code files, and automatically restart when the code changes.

{
    "restartable": "rs",
    "ignore": [
        ".git",
        ".svn",
        "node_modules/**/node_modules"
    ],
    "verbose": true,
    "execMap": {
        "js": "node --harmony"
    },
    "watch": [],
    "env": {
        "NODE_ENV": "development"
    },
    "ext": "js json"
}

7. Create the db directory and create two new files:

The configuration of the config.js database: 

module.exports = {
    host: 'localhost',
    user: 'root',
    password: '123456',
    database:'test',
    port: 5321,
    multipleStatements: true//允许多条sql同时执行
}

Index.js method of operating database

const mysql = require('mysql');
const config = require('./config');

function connect() {
    return mysql.createConnection({
        host: config.host,
        user: config.user,
        password: config.password,
        database: config.database,
        port: config.port,
        multipleStatements: config.multipleStatements//允许多条sql同时执行
    })
}

function querySql(sql) {
    const conn = connect()
    return new Promise((resolve, reject) => {
        try {
            conn.query(sql, (err, results) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(results)
                }
            })
        } catch (e) {
            reject(e)
        } finally {
            conn.end()
        }
    })
}

module.exports = {
    querySql
}

The method used is

db.querySql('select * from order').then(res => {
  console.log(res)
})

8, jwt verification

Generally, in our actual development, our interface must have an interface permission verification

Let me talk about where to put the token I have encountered. I usually put it in sessionStorage, which is the session of the page window. You can't get it when you open other windows. If you want to open other windows, you can get it. Use cookie Or localStorage, I won’t talk about the specific difference. There is another point I have encountered. The backend helps you set cookies. They set http-only and tick them. Our front end can’t be operated. They can. Compare the token change yourself, haha, continue to say jwt

module.exports = jwt({
  secret: 'zidingyi', // 秘钥自定义
  credentialsRequired: true
}).unless({
  path: [
    '/user/login' // 接口路由白名单不用做权限验证
  ]
})

How to use it as a middleware

const express = require('express')
const jwt = require('./jwt')
const router = express.Router()
router.use(jwt)

Guess you like

Origin blog.csdn.net/WDCCSDN/article/details/106617559