# Express middleware, custom middleware record

Express middleware, custom middleware

in fact, express a middleware function parameters specify
the middleware by using the method of use, the middleware performs synchronous, depends on the order in the parameter list

The official document to the definition of middleware

  • Execute any code
  • Change request and response objects. That can get the request object, thereby changing the request and response objects
  • The end of the cycle request and response.
  • Call stack next middleware.

The execution order of test middleware

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

//中间件
var myLogger = function(req,res,next){
    console.log('log...');
    //转向下一个路由或者中间件,如果注掉代码会卡在这里,没有放行
    next();
}

var requestTime = function(req,res,next){
    console.log(new Date().getTime());
    next();
}

//use应用中间件,执行顺序取决于参数列表顺序
app.use(requestTime,myLogger);

app.listen(3000,()=>{
    console.log("server run at port 3000...");
});
effect

Custom Middleware

Write a function in a js file and then export, you can call in at express
self.js

module.exports = function(){
    return function (req, res, next) {
        console.log("self middleware run ~~~");
        next();
    }
}

app.js

const express = require('express');
const self = require('./4self')();
const app = express();

//中间件
var myLogger = function(req,res,next){
    console.log('log...');
    //转向下一个路由或者中间件,如果注掉代码会卡在这里,没有放行
    next();
}

var requestTime = function(req,res,next){
    console.log(new Date().getTime());
    next();
}

//use应用中间件,执行顺序取决于参数列表顺序
app.use(requestTime,myLogger,self);

app.listen(3000,()=>{
    console.log("server run at port 3000...");
});

effect

Guess you like

Origin www.cnblogs.com/ltfxy/p/12528786.html