Getting the nodejs Express Middleware

Express Middleware

Express is a routing and Web middleware framework, its own function rarely. Middleware is a set of function calls on Express application nature.

I. Introduction

A request to the server, go through a life cycle, the server should: listening for requests - resolution request - in response to the request, the server when dealing with this process, sometimes very complicated, these complex business apart into a sub-section, sub-section is a mezzanine. For processing requests, prior to issuing the response can respond to the request and the stage to perform some operations and the processing result may be passed to the next processing step

Simply put, Express middleware (middleware) is the HTTP request handler. Its biggest feature is a middleware processed, before being passed to the next middleware. App instance during operation, will call a series of middleware.

img

Each middleware from App instance, three parameters, followed by the request object (representing an HTTP request), the object Response (representing an HTTP response), Next callback function (representing a next intermediate). Each middleware products for the HTTP request (request object) processing, and decides whether to call the method next, then the request object to the next intermediate. The following diagram image with more points:

img

The figure can be seen that the user's process water, is a http request, then through a series of intermediate processing, the process returns to give the final result.

ROLE

describes express middleware

1. execute any code.
2. Modify request and response objects.
3. End request - response cycle.
4. Call the next stack middleware

III. Classification

1. Application Middleware
2. Middleware route
3. Error processing middleware
4. Built middleware
5. The middleware to third
6. custom middleware

IV. Middleware

1. Global Use

const express = require("express");
const app = express();
/**
 * 全局使用,
 * 注意点,代码的顺序问题
 *  app.use 的语法
 *      app.use(PATH, [...HANDLER])
 *        - PATH 路径前缀,默认是 /
 *        - HANDLER   中间件函数,可以是多个
 */
app.use((req, res, next) => {
    console.log(1);
    //一定要使用next(),才会将控制器丢给下个中间件
    next();
}, (req, res, next) => {
    console.log(2);
    next();
}, (req, res, next) => {
    console.log(4);
    next();
});

app.get('/', (req, res, next) => {
    console.log(3);
    res.send("hello");
});

app.listen(3000, () => {
    console.log("服务启动成功");
});

2. When used globally, there must be a prefix condition

/**
 * 全局调用中间件,但是有前缀条件
 */

const express = require('express')
const app = express()

//这里是全局中间件  前缀条件是必须是有/hello的路由
app.use('/hello', (req, res, next) => {
  console.log('中间件1')
  next()
})

// GET http://localhost:3000/
app.get('/', (req, res) => {
  console.log('2')
  res.send('hello')
})

// GET http://localhost:3000/hello/world
app.get('/hello/world', (req, res) => {
  console.log(3)
  res.send('hello 1')
})


app.listen(3000, () => {
  console.log('服务启动成功')
})

3. For routing, local calls middleware

/**
 * 局部调用中间件(针对某个路由单独去调用)
 */

const express = require('express')
const app = express()

// 1. 定义一个中间件函数
const hello = (req, res, next) => {
  console.log('hi,大家好,我是渣渣辉')
  next()
}

//这里局部调用
// GET http://localhost:3000/
app.get('/', hello, (req, res) => {
  res.send('hello')
})

// GET http://localhost:3000/world
app.get('/world', (req, res) => {
  res.send('world')
})

app.listen(3000, () => {
  console.log('服务启动成功')
})

4. Custom middleware

const express = require('express');

const app = express();

// 自定义请求日志中间件
const logger = (req, res, next) => {
    console.log("Request Url:" + req.originalUrl);
    console.log("Request Method:" + req.method);

    console.log("Request Date:" + new Date().toLocaleString());
    // 必须要写
    next();
}

//自定义中间件,程序延迟执行
const setTimer = (timeout = 5000) => {
    return (req, res, next) => {
        setTimeout(() => {
            //延迟timeout执行
            console.log(`延迟${timeout}秒执行`);
            next();
        }, timeout);
    }
}

//全局调用中间件
app.use(logger);
app.use(setTimer(2000));

app.get('/hello', (req, res, next) => {
    console.log("进入get");
    res.send("结束");
});

app.listen(3000, () => {
    console.log("服务启动成功");
});

To summarize, in the actual development, in the middleware in the end what effect? ​​When a request is sent to the server, its life cycle is to receive a request (request), then the server process, transmit response (response) after treatment is over and this service back end processing process had to do a paper, imagine when business logic complex, in order to clarify and ease of maintenance, the need to deal with the points about things, to do the assignment into several parts, and each part It is a middleware.

5.app.use method

The method of use is registered express middleware, that is to say those who call middleware must use methods to get above the fourth point code can be seen, the use of app.use method, registered a 2 middleware to close http request to the first call logger middleware, and then make the appropriate treatment, the last method, control is passed by next () to a second middleware and then continue, if not next (), the program has been suspended last unresponsive

Published 18 original articles · won praise 49 · views 20000 +

Guess you like

Origin blog.csdn.net/liuqiao0327/article/details/105153247