中间件是什么呢?
中间件就是客户端http请求发起传送到服务器和服务器返回响应之间的一些处理函数。
为什么要使用中间件?
var express = require('express')
var app = express()
app.use(function(req,res) {
res.end('404 not found')
}
app.listen(3000,function(){
console.log('running...');
}
所有对该服务器的请求最终都会返回404 not found,无论是路径是什么
var express = require('express')
var app = express()
app.use('/public',function(req,res,next) {
res.end('you are public');
}
app.listen(3000,function(){
console.log('running...')
}
只要客户端访问该服务器的地址是以public开头(即127.0.0.1:3000/public/xxx),那么就会返回you are public 字符串
var express = require('express')
var app = express()
// 中间件1
app.get('/get/puclic',function(req,res){
res.end('get!');
}
// 中间件2
app.post('/post/public',function(req,res) {
res.end('post!');
}
app.listen(3000,function(){
console.log('running...');
}
客户端只有通过get方式访问127.0.0.1:3000/get/public时才会进入中间件1,只有通过post方式访问127.0.0.1:3000/post/public时才会进入中间件2,只有这两者完全匹配才会进入对应的中间件
以下面的代码为例进一步说明中间件的执行顺序
var express = require('express');
var app = express()
//中间件1
app.use(function(req,res) {
console.log('非严格');
})
//中间件2
app.use('/public',function(req,res,next) {
console.log('半严格');
next();
})
//中间件3
app.get('/public',function(req,res) {
console.log('严格 get');
})
//中间件4
app.post('/public',function(req,res) {
console.log('严格 post');
})
//中间件5
app.get('/public',function(req,res) {
console.log('严格 get');
})
app.listen(3000,function() { console.log('running...') })
此时客户端访问/public,那么首先会进入中间件1,因为有执行next函数,所以直接寻找后面能够匹配的中间件,进入中间件2,中间有执行next函数,所以进入中间件3,但是中间件3没有next函数,所以不再执行,所以输出的语句是‘非严格’ '半严格' '严格 get'
如果是下面代码,请求/public后结果又是怎样呢?
var express = require('express');
var app = express()
app.use('/img',function(req,res) {
console.log('半严格');
})
app.get('/public',function(req,res) {
console.log('严格 get');
})
app.post('/public',function(req,res) {
console.log('严格 post');
})
app.listen(3000,function() { console.log('running...') })
结果是输出'严格 get',请求到达服务器后,从上往下逐渐匹配,匹配到第二个中间件,进入执行,但是该中间件没有执行next函数,所以终止
综上所述,我们可以知道,第三方中间件的安装执行是有讲究的
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!
网友评论