同一个请求所通过的中间件,都是同一个请求对象和响应对象javascript
中间件函数中有三个基本参数, req、res、nextjava
注意:next的方法只是对中间件有用,对于其余的代码没有什么做用
复制代码
万能匹配(不关心任何请求路径和请求方法)express
app.use(function(req,res,next){
console.log('2')
next();
});
复制代码
只是以'/xxx/'开头的bash
app.use('/a',function(req,res,next){
console.log(req.url);
})
复制代码
路由过多时,代码很差管理。以大事件的代码为例,咱们定义了管理员角色的接口和普通游客的接口,这些接口若是全写在一个入口文件中(以下只是显示了4个接口,若是是40个接口,就会很难读了),是很很差维护的。 get:app
app.get('/',function(req,res,next){
res.end('Hello World!');
})
复制代码
post:dom
app.post('/',function(req,res,next){
res.end('Hello World!');
})
复制代码
put:函数
app.put('/user',function(req,res,next){
res.end('Hello World!');
})
复制代码
delete:post
app.delete('/user',function(req,res,next){
res.end('Hello World!');
})
复制代码
app.use(function(err,req,res,next){
consloe.error(err.stack);
res.status(500).end('something broke');
})
复制代码
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.....');
})
复制代码