中间件(middleware)就是处理HTTP请求的函数,用来完成各类特定的任务,好比检查用户是否登陆、分析数据、以及其余在须要最终将数据发送给用户以前完成的任务。 它最大的特色就是,一个中间件处理完,能够把相应数据再传递给下一个中间件。html
一个不进行任何操做、只传递request对象的中间件,大概是这样:express
function Middleware(request, response, next) { next(); }
上面代码的next为中间件的回调函数。若是它带有参数,则表明抛出一个错误,参数为错误文本。app
function Middleware(request, response, next) { next('出错了!'); }
抛出错误之后,后面的中间件将再也不执行,直到发现一个错误处理函数为止。若是没有调用next方法,后面注册的函数也是不会执行的。函数
和get函数不一样app.all()函数能够匹配全部的HTTP动词,也就是说它能够过滤全部路径的请求,若是使用all函数定义中间件,那么就至关于全部请求都必须先经过此该中间件。ui
格式:app.all(path,function(request, response));url
以下所示,咱们使用all函数在请求以前设置响应头属性。code
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函数。htm
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方法不只能够调用中间件,还能够根据请求的网址,返回不一样的网页内容,以下示例:
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属性,判断请求的网址,从而返回不一样的内容。
原文连接描述