Explore Express routing and middleware

1. Introduction of Express

Express is a minimalist, flexible Web application development framework based on the Node. js platform. It provides a series of powerful features to help you create a variety of web and mobile applications

Express Framework core features:

  1. Middleware can be set up to respond to HTTP requests

  2. Routing tables are defined for performing different HTTP request action (URL = resource) mappings

  3. You can render HTML pages dynamically by passing parameters to templates

2. Install

Enter CNPM install Express-g on the CLI to perform the global installation

Routing and middleware

Before use, introduce Express

var express = require('express');
var app = express();
Copy the code

routing

How does the routing representation handle the path part of an HTTP request

http://host:[port]/[path]
Copy the code

Example:

app.get('/',function(req,res){
    res.send('hello world')
})
Copy the code

In the above example, get can be replaced with POST or another request method. The first argument of the method is ‘/’ to match all paths, which can be paired with a regular expression or other method, and the second argument is the function to execute

The middleware

Middleware is a function that executes before the server receives a request and sends a response. Middleware is a function, It can access request objects (Request Object (REQ)), response objects (Response Object (RES)), and middleware in the request-response cycle of a Web application, usually named next. Middleware features include:

  • Execute any code.
  • Modify the request and response objects.
  • Terminates the request-response loop.
  • Call the next middleware in the stack.
  • If the current middleware does not terminate the request-response loop, the next() method must be called to hand control to the next middleware, or the request will hang.

Use app.use to insert a piece of middleware before a request or response

App. use(function(req,res,next){// Perform some code next(); })Copy the code

You can have multiple middleware, and next means to let the later middleware continue processing