Node个人学习(三)----数据解析与自定义中间件
GET数据解析:
使用自带的req.query进行解析
console.log(req.query);
POST数据解析:
1、body-parser模块解析数据------------form表单中的enctype=‘默认值’
使用中间件(body-parser)加工一次后再使用req.body进行解析,若不进行加工,req.body解析出来的将是undifine
const bodyParser=require("body-parser"); //导入中间件 var server=express(); //创建服务 server.use(bodyParser.urlencoded({})); //中间件加工 //中间件可以有两个参数:如下(可以不写) //server.use(bodyParser.urlencoded({ //extended:true; //扩展模式 //limit: 2*1024*1024 //大小限制 2MB ,默认大小:100KB //})); console.log(req.body); //解析
2、multer模块解析文件---------------form表单中的enctype=‘multipart/form-data’
const multer=require('multer'); var objMulter=multer({dest:'文件路径'}); server.use(objMulter.any()); server.use(function (req, res){ req.files[0].originalname //文件原始名(a.txt) req.files[0].path //文件存在服务器名称,不含扩展名(upload/aadfaew324we34) }); //把扩展名加上 //'upload/aadfaew324we34' + '.txt' //'upload/aadfaew324we34.txt' var newName=file.path+pathLib.parse(file.originalname).ext; fs.rename(老名, 新名, function (err){});
自定义中间件:
利用next和node的数据保留原理,
server.use(function(req,res,next){ ...中间件逻辑内容... next(); });