前言
这可能是习惯造成的,因为每一次自定义中间件的时候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()的使用位置