Middleware<中间件>

什么是中间件?

中间件(middleware)就是处理HTTP请求的函数,用来完成各种特定的任务,比如检查用户是否登录、分析数据、以及其他在需要最终将数据发送给用户之前完成的任务。 它最大的特点就是,一个中间件处理完,可以把相应数据再传递给下一个中间件。

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

function Middleware(request, response, next) { 
   next();
}

上面代码的next为中间件的回调函数。如果它带有参数,则代表抛出一个错误,参数为错误文本。

function Middleware(request, response, next) { 
   next('出错了!');
}

 抛出错误以后,后面的中间件将不再执行,直到发现一个错误处理函数为止。如果没有调用next方法,后面注册的函数也是不会执行的。

all函数的基本用法

和get函数不同app.all()函数可以匹配所有的HTTP动词,也就是说它可以过滤所有路径的请求,如果使用all函数定义中间件,那么就相当于所有请求都必须先通过此该中间件。

格式:app.all(path,function(request, response));

如下所示,我们使用all函数在请求之前设置响应头属性。

var express = require("express");
var app = express();
 
app.all("*", function(request, response, next) {
    response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });      //设置响应头属性值
    next();
});
 
app.get("/", function(request, response) {
    response.end("欢迎来到首页!");
});
 
app.get("/about", function(request, response) {
    response.end("欢迎来到about页面!");
});
 
app.get("*", function(request, response) {
    response.end("404 - 未找到!");
});
 
app.listen(80);

上面代码参数中的“*”表示对所有路径有效,这个方法在给特定前缀路径或者任意路径上处理时会特别有用,不管我们请求任何路径都会事先经过all函数。

use基本用法1

use是express调用中间件的方法,它返回一个函数。

格式:app.use([path], function(request, response, next){});

可选参数path默认为"/"。

app.use(express.static(path.join(__dirname, 'public')));

如上呢,我们就使用use函数调用express中间件设定了静态文件目录的访问路径。

如何连续调用两个中间件呢,如下示例:

var express = require('express');
var app = express();
 
app.use(function(request, response, next){
    console.log("method:"+request.method+" ==== "+"url:"+request.url);
    next();
});
 
app.use(function(request, response){
    response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
    response.end('示例:连续调用两个中间件');
});
 
app.listen(80);

use基本用法2

use方法不仅可以调用中间件,还可以根据请求的网址,返回不同的网页内容,如下示例:

var express = require("express");
var app = express();
 
app.use(function(request, response, next) {
   if(request.url == "/") {
      response.send("Welcome to the homepage!");
   }else {
      next();
   }
});
 
app.use(function(request, response, next) {
   if(request.url == "/about") {
     response.send("Welcome to the about page!");
   }else {
     next();
   }
});
 
app.use(function(request, response) {
  response.send("404 error!");
});
app.listen(80);

上面代码通过request.url属性,判断请求的网址,从而返回不同的内容。

原文链接描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值