Using the express write interface

Keywords: Database npm Mongoose JSON

1, Interface development specification (Restful API)

1. Clear needs

Function: to ensure that everyone's writing specifications are the same
Give an example:

The back end publishes the resource to the URL - > the front end accesses the resource through the URL - > and indicates the operation to be performed on the resource through the HTTP verb
Back end definition interface - > front end request interface - > HTTP verb table name operation purpose (get get post new put update, etc.)

  • Lift up the chestnut
    List page: access - / module name (get)
    Detail page: access - / module name / number (get)
    Add page: access - / module name / create (get)
    Processing: access - / module name (post)
    Modification page: access - / module name / number / edit (get)
    Processing: access - / module name / number (put)
    Delete: access - / module name / number (delete)

HTTP verbs: get, post, put, delete

2, Initialization (express scaffolding)

Scaffold: it's a term, which can't be explained clearly

Function: project code can be generated through scaffolding

1. Generate express framework code Express

Step 1: install the frame generator (NPM install express generator - G)


Step 2: generate the shop project (express project name) through the just installed express command

Step 3: install the framework dependency module
  • cd shop
  • npm install
Step 4: Start & access the test (pay attention at foot: Command npm start)

So far, the express framework has been set up. Connect to the database and modularize

1. Connect to database (Modular)
  • Step 1: encapsulate global functions & Global profiles

Create the file common/config.json

{
	"db_config":{
		"host" : "localhost",  
		"port" : 27017,   // Port number of the database
		"dbname" : "sixbuyshop"  // Database name
	}
}

Create the file common/db.js

Note: before copying the following code, first [npm i mongoose]

// Import module
const mongoose = require('mongoose');
// Import profile
const configObj = require(process.cwd() + "/common/config.json").db_config

// Connect to database
const db = mongoose.createConnection(`mongodb://${configObj.host}:${configObj.port}/${configObj.dbname}`, {useNewUrlParser: true, useUnifiedTopology: true}, (err)=>{
    if(err){
        console.log('---------------------------------------')
        console.log('Database connection failed:', configObj)
        console.log('---------------------------------------')
        return;
    }
    console.log('Database connection successful');
})

// Declare that global variables can be used globally
global.db = db

Create the file common/utils.js

// http protocol status code (can't tell through random check tomorrow night for 30 times)
// 2XX success
// 		200 - successful normal return (the server has successfully processed the request)     
// 		201 - data created successfully (indicates that the server has executed successfully and a new resource has been created)     
// 		202 accepted (request accepted by server but not processed)
// 3XX redirection (the server returns information to inform the browser how to do subsequent operations to successfully process the request)
//      301 permanent (new website)
//      302 - temporary (station jump)
//      304 browser cache (the request is successfully detected that the modified data comes from the browser)
// 4XX client error (client reason, hindering server processing)
//      400 front end request failed, wrong mode parameter
//      401 authentication information without HTTP authentication (scenario: webpage login failure)
//      403 - no access (private warehouse of code cloud)
//      404 - file does not exist
//      405 - wrong request method 
// 5XX server error
//		500 server side error executing request
//		503 - server overloaded, unable to process request
// -------------------------------

/**
 * Interface response
 * @param {Object} res      Response object
 * @param {Number} code     Status code
 * @param {String} message  Prompt information
 * @param {mixed}  data     Response data
 */
global.sendJson = (res, code, message, data = null) => {
    res.json({
        "meta" : {
            "state" : code,
            "msg" 	: message
        }, 
        "data" : data
    });
}

Import database configuration of import file

require(process.cwd() + "/common/db.js")
require(process.cwd() + "/common/utils.js")

Two, routing
1. Step 1 establish route

Setting up the routing module of home page under routes directory

var express = require('express');
var router = express.Router();

// I used to write logic directly here
// But I don't know how many routes
// Solution: go to the controller directory to define the call here
// process.cwd() indicates the file path of command execution
//const { getHomeBannerList } = require(process.cwd() + '/controller/home')

// Home page broadcast
// router.get('/', getHomeBannerList )

/* GET users listing. */
router.get ('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

Import activation route in app.js file


Using mvc idea to separate logic code
Model model - responsible for data processing,
View view - responsible for displaying pages
Controller controller - responsible for scheduling which M and which V to use

Establishing controller/home.js is responsible for calling methods under model

// const  { usersGetList } = require(process.cwd() + "/model/home")


  //User list
const getHomeBannerList = async (req, res, next) =>{
      // const userData =await usersGetList()
      sendJson(res, 200, "Successful operation")
      // console.log(req.body)
      
    // const insertObj = req.body
    // const cbData=await usersModelPost(insertObj);

    // if(cbData){
    //     sendJson(res, 200, "operation succeeded", cbData)
    // }else{
    //     sendJson(res, 500, "operation failed", cbData);
    // }

}

module.exports={
  getHomeBannerList
}

Build model/home.js and write some logic code to request the database

const model = db.model('user',{
	name:{type:String},
    pwd:{type:String},
	sex:{type:String, default:"female"}
})
// Query of user list

const  usersGetList = ()=>{
    return model.find()  
      .then(res=>{
          return res
      })
      .catch(err=>{
          console.log('User name query error:'+ err)
          return null
      })
 }

module.exports={
    usersGetList
}
Published 24 original articles, won praise 6, visited 4080
Private letter follow

Posted by nivosh on Thu, 05 Mar 2020 01:23:39 -0800