preface

1.MVC

MVC is a layered pattern for the back end: Model, View, Controller

  • Model Data connection layer
  • View the view layer
  • The controller control layer
    • Router Distributes routes
    • Service Business processing

Restful interface specifications and traditional interface specifications

1. Restful specifications + get Users Obtain all resources + Get Users /:id Obtain resources by ID + Post Users Add resources + Put Users /: ID Update resources. Patch users/:id: delete users/:id: delete users/:id: delete users/:id Traditional specification + Get getUsers + Get getUsersById + POST addUsers + POST updateUsers + Get deleteUsersCopy the code

3. Apidoc automatically generates interface documents

1. Installation environment

npm i apidoc -g
Copy the code

2. Create apidoc.json in the root directory of the project

{
    "name":"example"."version":"0.1.0 from"."description":"apidoc basic example"."title":"Custom apiDoc browser title"."url":"https://api.github.com/v1"
}
Copy the code

3. Create the apidoc folder in the root directory of the project. 4

/ * * *@api {get} /user/:id Request User information
  * @apiName GetUser
  * @apiGroup User
  *
  * @apiParam {Number} id Users unique ID.
  *
  * @apiSuccess {String} firstname Firstname of the User.
  * @apiSuccess {String} lastname  Lastname of the User.
  * @apiSuccessExample {json} Success-Response:
  *     HTTP/1.1 200 OK
  *     {
  *       "firstname": "John",
  *       "lastname": "Doe"
  *     }
  */
Copy the code

5. Generate interface documents

apidoc -i ./router -o ./apidoc
Copy the code

practice

1. Apidoc. Json file:

{
"name": "example"."version": "0.1.0 from"."description": "The coolest interface document ever."."title": "Hero management"."url": "http://127.0.0.1:3000"
}
Copy the code

2. Comment the interface

/** Get hero *@api {get} /users 1.1 Get heroes *@apiName GetUser
* @apiGroup User
*
* @apiParam {null} null null
*
* @apiSuccessExample {json} Success- the Response: HTTP / 1.1 * 200 OK {" status ": 0," message ": [{" id" : 2, "name" : "I don't know sun", "age" : 16, "sex" : "female", "isdel" : 0, "add_time" : the null}, {" id ": 3," name ":" ban ", "age" : 2, "sex" : "demon", "isdel" : 0, "add_time" : null}, {" id ": 5, "name", "lian", "age" : 30, "sex", "male" and "isdel" : 0, "add_time" : null}, {" id ": 7," name ":" guan yu ", "age" : 18, "sex" : "Demon", "isdel" : 0, "add_time" : null}, {" id ": 11," name ":" wang ", "age" : 28, "sex", "female", "isdel" : 0, "add_time" : "The 2021-05-27 11:09:55"}, {" id ": 12," name ":" 111 "wang zhaojun," age ": 28," sex ":" female ", "isdel" : 0, "add_time" : "2021-05-27 11:08:50"}]} */

/** Get hero resources by *@api {get} /users/:id 1.2 Obtain the hero resource * based on the ID@apiName GetUserById
* @apiGroup User
*
* @apiParam {Number} Id User ID * *@apiSuccessExample {json} Success- the Response: HTTP / 1.1 * 200 OK {" status ": 0," message ": [{" id" : 2, "name" : "I don't know sun", "age" : 16, "sex" : "female", "isdel" : 0, "add_time": null } ] } */

/** Add hero *@api {post} /users 1.3 Add heroes *@apiName AddUserById
* @apiGroup User
*
* @apiParam {String} Name User name (mandatory) *@apiParam {Number} Age User age (mandatory) *@apiParam {String} Sex User gender (mandatory) * *@apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK {"status": 0, "message": 'success'} */

/** Update hero *@api {put} /users/:id 1.4 Update hero *@apiName UpdatedUserById
* @apiGroup User
*
* @apiParam {Number} Id User ID (mandatory) *@apiParam {String} Name User name (mandatory) *@apiParam {Number} Age User age (mandatory) *@apiParam {String} Sex User gender (mandatory) * *@apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK {"status": 0, "message": 'success'} */

/** Delete hero *@api {delete} /users/:id 1.5 Delete hero *@apiName DeletedUserById
* @apiGroup User
*
* @apiParam {Number} Id User ID (mandatory) * *@apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK {"status": 0, "message": 'success'} */
Copy the code

Entry file :(index.js)

1. Introduce modules

const express=require('express')
const path=require('path')
Copy the code

2. Create a service

const app=express()
Copy the code

3. Configure cross-domain

app.use(require('cors') ())Copy the code

4. Connect the files in the apidoc folder

app.use(express.static(path.join(__dirname,'./apidoc')))
Copy the code

5. Parse the data

app.use(express.urlencoded({extended:false}))
app.use(express.json())
Copy the code

6. Import index.js from the router

require('./router/index.js')(app,express)
Copy the code

7. Listen to the port

app.listen(3000['10.41.153.32'.'127.0.0.1'].() = >{
    console.log('Local Services http://127.0.0.1:3000')
    console.log('Remote Services http://10.41.153.32:3000')})Copy the code

Router file (./routes/index.js)

module.exports = (app, express) = > {// expose the entry file index.js
  const ctrl = require('.. /controller')// Get the function of the control layer
  const router = express.Router()

  // Request resources
  router.get('/users', ctrl.getUsers)

  // Request resources by id
  router.get('/users/:id', ctrl.getUserById)

  // Add resources
  router.post('/users', ctrl.addUser)

  // Update resources by ID
  router.put('/users/:id', ctrl.updateUser)

  // Delete resources by id
  router.delete('/users/:id', ctrl.deleteUser)

  app.use(router)
}
Copy the code

Control layer file (./controller/index.js)

const db = require('.. /db')// Import the data connection file
const moment = require('moment')
module.exports = {// Expose the routing file
  async getUsers(req, res) {
    try {
      const sql = 'select * from user where label = 0'
      const { results } = await db.query(sql)
      res.send({
        status: 0.message: results
      })
    } catch (error) {
      res.send({
        message: error
      })
    }
  },
  async getUserById(req, res) {
    try {
      const sql = 'select * from user where label = 0 and id = ? '
      const { results } = await db.query(sql, req.params.id)
      if (results.length === 0) return res.send({ status: 1.message: 'Heroes do not exist' })
      res.send({
        status: 0.message: results
      })
    } catch (error) {
      res.send({
        message: error
      })
    }
  },
  async addUser(req, res) {
    try {
      const sql = 'insert into user set ? '
      const body = req.body
      body.add_time = moment().format('YYYY-MM-DD HH:mm:ss')
      const { results } = await db.query(sql, body)
      if(results.affectedRows ! = =1) return res.send({ status: 1.message: 'Add failed' })
      res.send({
        status: 0.message: 'success'})}catch (error) {
      res.send({
        message: error
      })
    }
  },
  async updateUser(req, res) {
    try {
      const sql = 'update user set ? where id = ? '
      const body = req.body
      body.add_time = moment().format('YYYY-MM-DD HH:mm:ss')
      const { results } = await db.query(sql, [body, req.params.id])
      if(results.affectedRows ! = =1) return res.send({ status: 1.message: 'Update failed' })
      res.send({
        status: 0.message: 'success'})}catch (error) {
      res.send({
        message: error
      })
    }
  },
  async deleteUser(req, res) {
    try {
      const sql = 'update user set label = 1 where id = ? '
      const { results } = await db.query(sql, req.params.id)
      if(results.affectedRows ! = =1) return res.send({ status: 1.message: 'Delete failed' })
      res.send({
        status: 0.message: 'success'})}catch (error) {
      res.send({
        message: error
      })
    }
  }
}

Copy the code

Connect layer file (./db/index.js)

module.exports = {// Expose the controller file
  query(sql, params = []) {
    return new Promise((resolve, reject) = > {
      // 1. Import mysql
      const mysql = require('mysql')
      const dbConfig = require('./db.config')// Import the database connection file

      // 2. Create connection objects
      const connection = mysql.createConnection(dbConfig)

      // 3. Enable the connection
      connection.connect(err= > {
        if (err) return reject(err.message + '---- database connection failed ')
        console.log('Database connection successful')})// 4. Execute the query statement
      connection.query(sql, params, (err, results, filds) = > {
        if (err) return reject(err.message)
        resolve({
          results,
          filds/ / field})})5. Close the connection
      connection.end(err= > {
        if (err) return reject(err.message)
        console.log('Close database connection')})})}}Copy the code

Connect to database (./db/db.config.js)

module.exports = {
  host: '127.0.0.1'.user: 'root'.password: 'root'.database: '2101 _3'
}
Copy the code

Add, delete, change and check rendering to the page

Home page: index. HTML

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> <link rel="stylesheet" href="./ CSS /bootstrap.min. CSS "> </head> <body> <div Class ="container"> <h1> Hero management </h1> <a href="./add.html" class=" BTN btn-success pull-right"> Add </a> <table class="table Table - striped table - hover "> < thead > < tr > < th > serial number < / th > < th > name < / th > < th > age < / th > < th > gender < / th > < th > time < / th > < th > action < / th > < / tr > </thead> <tbody id="tbody"> </tbody> </table> </div> <script src="./js/jquery.min.js"></script> <script> function getUsers() { $(function () { $.ajax({ url: 'http://10.41.153.32:3000/users', success(res) { let html = '' res.message.forEach(item => { html += ` <tr> <td>${item.id}</td> <td>${item.name}</td> <td>${item.age}</td> <td>${item.sex}</td> <td>${item.add_time}</td> <td> <a href="./edit.html?id=${item.id}" class="btn </a> <button type="button" class=" BTN BTN -danger" data-id="${item.id}" id="deleteUsers"> delete </button> </td>  </tr> ` }) $('#tbody').html(html) } }) }) } getUsers() $('#tbody').on('click', '#deleteUsers', function () { // console.log($(this).data('id')) $.ajax({ type: 'delete', url: 'http://10.41.153.32:3000/users/' + $(this). The data (" id "), / / data () method to the selected elements of additional data, or to get the data from the selected elements. success(res) { console.log(res) // location.reload() getUsers() } }) }) </script> </body> </html>Copy the code

Add page: add.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> <link rel="stylesheet" href="./ CSS /bootstrap.min. CSS "> </head> <body> <div Class ="container"> <h1> Add hero </h1> <div class="form-group"> <label for=""> name </label> <input type="text" Class ="form-control" ID ="name" placeholder="Input field"> </div> <div class="form-group"> <label for=""> </label> <input type="text" class="form-control" id="age" placeholder="Input field"> </div> <div class="form-group"> <label For =""> gender </label> <input type="text" class="form-control" ID ="sex" placeholder=" input field"> </div> <button type="button" class="btn btn-primary" id="addForm">Submit</button> </form> </div> <script src="./js/jquery.min.js"></script> <script> $(function () { // 1. Access to the parameters passed $(' # addForm). Click (function () {var data = {name: $(' # name). Val (), age: $(' # age). Val (), sex: $('#sex').val() } // 2. Send an ajax request $. Ajax ({type: "post", url: 'http://10.41.153.32:3000/users', data, success (res) {the console. The log (res) / / 3. Manual to jump to the home page location. The href = '/'}})})}) < / script > < / body > < / HTML >Copy the code

Edit page: edit.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> <link rel="stylesheet" href="./ CSS /bootstrap.min. CSS "> </head> <body> <div Class ="container"> <h1> <form id="editForm"> </form> </div> <script SRC ="./js/jquery.min.js"></script> <script>  $(function () { // const id = location.search.split('=')[1] const params = new URLSearchParams(location.search) const id = params.get('id') $.ajax({ url: 'http://10.41.153.32:3000/users/' + id, Success (res) {let HTML = '<div class="form-group"> <label for=""> name </label> <input type="text" class="form-control" Id ="name" value="${res.message[0]. Name}"> </div> <div class="form-group"> <label for=""> age </label> <input type="text" Class ="form-control" id="age" value="${res.message[0].age}"> </div> <div class="form-group"> <label for=""> Gender </label> <input type="text" class="form-control" id="sex" value="${res.message[0].sex}"> </div> <button type="button" class="btn btn-primary" id="editUsers">Submit</button> ` $('#editForm').html(html) } }) // 1. $('#editForm').on('click', '#editUsers'), function () {console.log(1) var data = {name: $('#name').val(), age: $('#age').val(), sex: $('#sex').val() } // 2. Send an ajax request $. Ajax ({type: 'put' url: 'http://10.41.153.32:3000/users/' + id, data, success (res) {/ / 3. Manual to jump to the home page location. The href = '/'}})})}) < / script > < / body > < / HTML >Copy the code