1 framework

  • A semi-product that is used to quickly solve a certain type of problem follows the usage specifications of the framework: Bootstrap, Lay-UI, Express, Vue, react

2 the library

  • JQuery, dayJS, underscore, Lodash, Art-Template, Axios, echart, zepto.js

3 web development

  • Running on Node.js, it can display pages for different requests and provide interface services

4 Framework Use

  • Res.send () is a supplementary method that the Express framework provides to the RES object (the RES in the HTTP module does not have this method) to end the request, as well as res.json(), res.sendfile ().
Initialize the package.json file
npm install --yes
// Install express locally
npm i express
/ / use
/ / load express
const express = require('express')
/ / call express
const server=experss()
// Set the handler for the request, using get as an example
server.get('/'.(req,res) = >{
  res.send('hello world')})// Listen on the port number to start the service
server.listen(10086.() = >{
  console.log('Services to start')})Copy the code

5 Express Static resource hosting

  • Target: Contents in a folder can be accessed directly
  • Server.use (express.static (‘ directory name ‘)) server.use (express.static (‘ directory name ‘))
  • Use with access prefix: server.use(‘/ XXX ‘, express.static (‘ directory name ‘)) // To access the content in XXX, you must add/XXX to the request URL

6 Route and Interface

  • It’s called a route in the back and an interface in the front
  • Convention: When a user accesses the XX address, the XXXX logic is executed
  • Format: server. request type (request address, callback function)
  • Example: server.get (‘/getInfo’, (req, res) => {res.json(XXXXX)}) // When the user requests /getInfo as get, the subsequent callback is performed to return the data in JSON string format

7 Express-get Request – No parameter

const express = require('express')
const server = express()

// http://localhost:10086/get
server.get('/get'.(req, res) = > {
    res.send('123')
})

server.listen(10086.() = > {
    console.log('Port 10086 started:');
})
Copy the code

8 Express-get Request – With parameters

  • The Express framework automatically collects the query string parameters that get passes from the URL address and stores them in the Query property of the REQ object.
const express = require('express')
const server = express()

// http://localhost:10086/get? Name = li bai
server.get('/get'.(req, res) = > {
    res.send(req.query)
})

server.listen(10086.() = > {
    console.log('Port 10086 started:');
})
Copy the code

9 express – post request

  • Post request parameters In the request body, there are three cases for parameters
  1. Normal key-value pairs
  2. Json object
  3. File upload
  • server.use(….) The res.body property is then added to res.body to parse out the data carried in the request body and store it in req.body

10 Express-POST request – Plain key-value pair parameters

const express = require('express')
const server = express()

// Parse out the normal key-value pairs carried in the request body and store them in req.body
server.use(express.urlencoded())
// Routing - interface
server.post('/add'.(req, res) = > {
    console.log(req.body)
    res.json(req.body)
})

server.listen(10086.() = > {
    console.log('Port 10086 started:');
})
Copy the code

11 Express-POST request – Data in JSON format

const express = require('express')
const server = express()

// The json data carried in the request body is parsed and stored in req.body
server.use(express.json())
// Routing - interface
server.post('/postJSON'.(req, res) = > {
    console.log(req.body)
    res.json(req.body)
})

server.listen(10086.() = > {
    console.log('Port 10086 started:');
})
Copy the code

12 Express – Post request -formData format data

  • Additional use of the third-party package Multer is required
  • upload.singleIt just handles file uploads
const express = require('express')
const server = express()

// For file uploads, an additional third-party package multer is required
// Install multer
/ / use
/ / into the bag
const multer = require('multer')
// Set uploads to a directory where file uploads will be saved
const upload = multer({ dest: 'uploads/' })
/ / use
server.post('/postfile', upload.single('cover'), (req, res) = > {
    console.log(req.file)  // Record the file upload information
    console.log(req.body)  // Other common parameters are recorded
    res.json('Data upload successful! ')
})

server.listen(10086.() = > {
    console.log('Port 10086 started:');
})
Copy the code

13 Understand interface parameter transmission

  • Parameter location: request line, request body
  • In the request body, there is a content-type attribute that specifies the format in which the parameters passed in the request body should be parsed
  • Four processing methods:

14 Require loading mechanism

15 Understand restful interfaces

  • Designing resources through urls, interfaces are generally nouns, not verbs
  • Request mode GET, POST, DELETE, and PUT Determine the operation type of the resource
  • There are five different request ways to specify the type of operation:
    1. Get access to
    2. The post to add
    3. Delete delete
    4. Put Modification-overwrite
      1. let obj = { a : 1 }
      2. obj = { b : 1 }
    5. Patch modification – Partial modification
      1. let obj = { a : 1 }
      2. obj . a = 2

16 middleware

  • It means that a complex function is divided into many small links, and the processing logic of each link is called middleware
  • In Express code, middleware is everywhere
  • Classification:
  1. Application-level middleware
  2. Routing level middleware
  3. Built-in middleware
  4. Error handling middleware
  5. Third-party middleware
  • Define the format and use process
    1. Sequential execution of middleware, the order in which the code is written
    2. If there is no next and no end in the middleware, it will get stuck
    3. If next is used, the next middleware is moved in order
// Named function format:
const handler = (req, res, next) = > {
  console.log(Date.now());
  next();
}
server.use(handler);


// Anonymous function format:
app.use((req, res, next) = > {
  console.log(Date.now());
  next();
});


Copy the code

Middleware – Four matching rules

Server.use (Middleware)// It is application-level middleware that matches all requests
server.use('/apiname'Middleware)// Matches requests whose request path is /apiname
server.get('/apiname'Middleware)// Matches a request of type GET with a request path of /apiname
server.get('/apiname', the middleware1, the middleware2) // A route uses multiple middleware
Copy the code

18 Routing Middleware

  • Function:
  1. It helps us write interfaces of different classes in different files and then combine them
  2. Conducive to division of labor, easy to maintain the code
  • Operation steps:

    1. Organize existing interfaces

    2. Write interfaces and export data by module

// Clean up existing interfaces
// Write interface by module, export
const express = require('express')
const router = express.Router()

// Write the interface module
router.get('/getinfo'.(req, res) = > {
    res.send('Got the getInfo')
})
router.get('/getdetail'.(req, res) = > {
    res.send('got the getdetail')})/ / export
module.exports = router
Copy the code

3. Use it in the main file

// Configure the server
const express = require('express')
const app = express()
app.listen(10086.() = > {
    console.log("Server started");
})

// Import the routing object
const adminRouter = require('./router/admin') // Define the relative path of the interface module
// Routing middleware
app.use('/admin', adminRouter)

Copy the code

19 cross-domain

  • Reason: Ajax from different sources
  • Cognate: the protocol, domain name, and port are the same. If there’s one difference, it’s a different source
  • Cause: The browser must comply with the same origin policy. The browser considers that the request is insecure, so an error is reported. The server receives and processes requests normally

  • Solution:
  1. Add a special response header for this response: access-Control-allow-Origin
  2. Using cors package
    1. Install: NPM I CORS
    2. Introduce: const cors = require (‘ cors’)
    3. Use server.use (cors()) as middleware
  • As a front end, postman is used to check if the interface is working properly in case of cross-domain problems encountered during development

    1. Normal: Indicates that the cross-domain problem is not handled and you can negotiate with the backend

    2. Abnormal: An Ajax request error may occur