自定义中间件使用
- custom-body-parse.js
const qs =require('querystring');//1.导入nodejs中的querystring模块
const bodyParser =(req,res,next)=>{
//定义中间件的具体业务逻辑
//1.定义一个str字符串,用于存储客户端发送的请求体数据
let str ='';
//2.监听req的data事件,str中存储完整的请求体数据
req.on('data',(chunk)=>{
str+=chunk;
});
//3.监听req的end事件
req.on('end',()=>{
req.body =qs.parse(str);//把字符串格式的请求数据,解析成对象格式
next();
})
}
module.exports = bodyParser;
- custom-index.js
const express =require('express');
const app =express();
//导入自己封装的中间件模块,将自定义的中间件函数,注册为全局可用中间件
app.use(require('./custom-body-parse.js'));
app.post('/user',(req,res)=>{
res.send(req.body);//响应出对应的请求提数据
})
//调用app.listen 方法,指定端口号并启动web服务器
app.listen(80,function(){
console.log('Express Server Running at http://127.0.0.1');
})
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/17024223.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。
