自定义中间件使用

  • 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');
})

posted @ 2023-01-04 10:39  码农阿亮  阅读(25)  评论(0)    收藏  举报