To read more articles in this series please visit myMaking a blog, sample code please visithere.

Express introduced

Based on node. js platform, fast, open, minimalist Web development framework.

Express is characterized by being easy to get started and extending its functionality with a variety of middleware.

However, because Express was developed relatively early, it mainly used callback functions for asynchronous operations, and could not use Async functions, so the original team also developed Koa with more powerful functions to solve the shortcomings of Express.

Still, Express is an essential skill for developers.

Create a server using Express

Example code: /lesson01/server.js

  1. in/lesson01Folder passnpm init -yInitialize the project
  2. usenpm install express --saveInstall Express
  3. Reference Express and create a server
const express = require('express')

const server = express()

server.listen(8080)

console.log(`Server started at 8080`)
Copy the code

Common route configuration methods

Example code: /lesson01/server.js

More than get methods are commonly used to receive requests:

  1. server.get, processing get requests
  2. server.postTo process post requests
  3. server.use, the first route parameter of the method can be omitted. In this case, all interface requests are processed, as follows:
server.use('/first', (req, res, next) => {
  console.log('first')
  next()
})
Copy the code

In addition to these three methods, there are server.put, server.delete, and other methods to view the document

Add the routing

Example code: /lesson01/server.js

Express provides routing functionality that allows you to add routes without reference to middleware.

server.get('/first', (req, res, next) => {
  res.send({
    error: 0,
    msg: 'Request successful'})})Copy the code

The code meaning is as follows:

  1. A route to the GET request was created.
  2. The first argument ‘/first’ indicates the route name of the request.
  3. The second argument is the callback function.
  4. The callback function data transfer parameter REq represents the instance of the request parameter.
  5. The callback function data transmission parameter RES represents the response parameter instance.
  6. Next triggers the next operation.
  7. Res. send can send data to the console. Unlike the res.write method of native Node.js, res.write can send data directly, such as JSON, as well as buffers and strings, as follows:
res.send(new Buffer('wahoo'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.send(404, 'Sorry, cant find that');
res.send(404);
Copy the code

http://localhost:8080/first at this time, you can see page shows: {” error “: 0,” MSG “:” request is successful “}.

Use of the next method

Example code: /lesson01/server.js

The next method is used for multiple levels of processing of requests, for example:

server.get('/second', (req, res, next) => {
  if(Number(req.query.num) > 10) {// The next route with the same name is triggered only when the condition is met. next() }else {
    res.send({
      error: 1,
      msg: 'Please enter a number greater than 10'
    })
  }
})

server.get('/second', (req, res, next) => {
  res.send({
    error: 0,
    msg: 'Entered successfully'})})Copy the code

The code meaning is as follows:

  1. If multiple routes with the same name are configured, the code executes sequentially from top to bottom, but if the next method is not called, the execution is interrupted.
  2. If the interface transfer for http://localhost:8080/second? If num=8 and num > 10 is not met, the code in the second /second route callback function will not be executed.
  3. If the interface transfer for http://localhost:8080/second? Num =80. If num > 10 is met, execute the code in the second /second route callback function and proceed to the next step.
  4. The next method is useful when dealing with middleware because it can be used to determine whether the next level of processing needs to be performed at all levels of middleware processing.

The next method passes parameters

Example code: /lesson01/server.js

Sometimes it is necessary to pass parameters to the next level of processing, just add attributes to the req instance directly, but be careful not to override the system default attributes, as follows:

server.get('/second', (req, res, next) => {
  if(Number(req.query.num) > 10) {// The next route with the same name is triggered only when the condition is met. req.randomNum = Math.floor(Math.random() * 100) next() }else {
    res.send({
      error: 1,
      msg: 'Please enter a number greater than 10'
    })
  }
})

server.get('/second', (req, res, next) => {res.send({error: 0, MSG: 'Input success, received random number is${req.randomNum}`})})Copy the code

Go to http://localhost:8080/second? Num =80; req. RandomNum =80;