Express中间件

中间件(middleware)就是处理http请求的函数,其最大的特点就是,一个中间件处理完成后传递给下一个中间件。

每个中间件可以从app实例,接收三个参数,依次为:request对象(代表HTTP请求)response对象(代表HTTP回应)next回调函数(代表下一个中间件),每一个中间件都可以对HTTP请求(request对象)进行加工,并且决定是否调用next方法,将request对象再传给下一个中间件

一个不进行任何操作、只传递request对象的中间件,就是下面这样:

function useMiddleware(req, res, next) {

  next();

}

  

上面代码的next就是下一个中间件。如果它带有参数,则代表抛出一个错误,参数就是错误的文本,如下:

function useMiddleware(req, res, next) {

  next('出错了');

  

抛出错误以后,后面的中间件就不在执行了,直到发现了一个错误处理函数为止

use方法

use注册中间件的方法,它返回一个函数

var express = require("express");var http = require("http");

var app = express();

 

app.use(function(request, response, next) {

  console.log("In comes a " + request.method + " to " + request.url);

  next();

});

 

app.use(function(request, response) {

  response.writeHead(200, { "Content-Type": "text/plain" });

  response.end("Hello world!\n");

});

http.createServer(app).listen(1337);

  

 

上面代码使用app.use方法,注册了两个中间件。收到HTTP请求后,先调用第一个中间件,在控制台输出一行信息,然后通过next方法,将执行权传给第二个中间件,输出HTTP回应。由于第二个中间件没有调用next方法,所以request对象就不再向后传递了

use方法内部可以对访问路径进行判断,据此来实现简单的路由,根据不同的请求网址,来返回不同的页面

var express = require("express");var http = require("http");

var app = express();

 

app.use(function(request, response, next) {

  if (request.url == "/") {

    response.writeHead(200, { "Content-Type": "text/plain" });

    response.end("Welcome to the homepage!\n");

  } else {

    next();

  }

});

 

app.use(function(request, response, next) {

  if (request.url == "/about") {

    response.writeHead(200, { "Content-Type": "text/plain" });

  } else {

    next();

  }

});

 

app.use(function(request, response) {

  response.writeHead(404, { "Content-Type": "text/plain" });

  response.end("404 error!\n");

});

 

http.createServer(app).listen(1337);

  

除了可以在回调函数内部判断请求的网址,use方法也允许将请求网址写在第一个参数,这代表只要请求路径匹配该参数,后面的中间件才能生效,如:

app.use('/path', someMiddleware); 

  

原文地址:https://www.cnblogs.com/9420i/p/10265068.html