自定义中间件使用next()很容易出错的点

前言 

        这可能是习惯造成的,因为每一次自定义中间件的时候next()是一定会调用的所以很有可能在创建函数的时候先写了next(),这就可能会造成问题

引入一个自定义的中间体

const qs = require('querystring');

const body_parser = (req, res, next) => {
    let str = '';
    req.on('data', (chunk) => {
        str += chunk;
    });

    req.on('end', () => {
        let body = qs.parse(str);
        req.body = body;
        console.log(req.body);
        console.log('----------');
    });
    next();
}

module.exports = {
    body_parser
};

问题: 

        可以发现next()在监听函数on('end',function)外使用了,但由于监听函数是异步任务next()被先执行了就会导致req.body = body  req.body 无法挂载成功,在主文件的路由中是无法使用req.body的它的值为 undefined

解决

const qs = require('querystring');

const body_parser = (req, res, next) => {
    let str = '';
    req.on('data', (chunk) => {
        str += chunk;
    });

    req.on('end', () => {
        let body = qs.parse(str);
        req.body = body;
        console.log(req.body);
        console.log('----------');
        next();
    });
}

module.exports = {
    body_parser
};

        当在中间体内使用监听函数时要非常注意next()的使用位置 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Heigl swift

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值