中间件概念
-
同一个请求所经过的中间件,都是同一个请求对象和响应对象
-
中间件函数中有三个基本参数, req、res、next
- req就是请求相关的对象,它和下一个中间件函数中的req对象是一个对象
- res就是响应相关的对象,它和下一个中间件函数中的res对象是一个对象
- next:它是一个函数,调用它将会跳出当前的中间件函数,执行中间件;如果不调用next,则整个请求都会在当前中间件卡住,而得不到返回。
注意:next的方法只是对中间件有用,对于其他的代码没有什么作用
1.1中间件的执行流程
1.2应用程序级别的中间件
万能匹配(不关心任何请求路径和请求方法)
app.use(function(req,res,next){
console.log('2')
next();
});
只是以'/xxx/'开头的
app.use('/a',function(req,res,next){
console.log(req.url);
})
1.3路由级别的中间件
路由过多时,代码不好管理。以大事件的代码为例,我们定义了管理员角色的接口和普通游客的接口,这些接口如果全写在一个入口文件中(如下只是显示了4个接口,如果是40个接口,就会很难读了),是很不好维护的。 get:
app.get('/',function(req,res,next){
res.end('Hello World!');
})
post:
app.post('/',function(req,res,next){
res.end('Hello World!');
})
put:
app.put('/user',function(req,res,next){
res.end('Hello World!');
})
delete:
app.delete('/user',function(req,res,next){
res.end('Hello World!');
})
1.4错误处理中间件
app.use(function(err,req,res,next){
consloe.error(err.stack);
res.status(500).end('something broke');
})
1.5 内置中间件
1.6第三方中间件
- body-parser
- multer(post上传文件中间件)
const express=require('express');
const path=require('path')
// Post文件上传时,我们需要使用multer中间件
const multer=require('multer');
const sr=require('string-random');
// 用来生成随机字符串的包,string-random
// 对multer进行配置
// 设置文件保存位置
// 设置文件上传名称
let upload=multer(multer.diskStorage({
storage:multer.diskStorage({
// 用来设置存储位置
destination:(req,res,callback)=>{
// 注意callback的参数1正常处理中必须是null
//参数2为地址需要采用绝对路径的方式
callback(null,path.join(__dirname,'./upload'));
},
// filename设置文件名
filename:(req,file,callback)=>{
// file是文件信息
// sr用来生成随机的字符串,初始纳入的数值为生成的字符串长度
// 参数名需要设置name
callback(null,sr(15)+file.originalname);
}
})
}));
let app=express();
// 设置时,需要在app.post参数2中设置upload.single()
app.post('/fileupload',upload.single('file'),(req,res)=>{
console.log(req.file);
res.end('ok');
});
app.listen(8888,()=>{
console.log('8888.....');
})