关于Express中使用next()函数遇到的执行顺序问题
前言
关于next()函数是什么,我就不用多说了,下面直接看代码。
一、代码介绍
这是一个自定义解析表单数据的中间件模块
二、代码
const express = require('express')
const app = express()
const qs = require('querystring')
// 这是解析表单数据的中间件
app.use(function (req, res, next) {
// 监听req对象的data事件,来获取客户端发到服务器的数据
let str = '';
// 监听data事件,拼接数据
req.on('data', (chunk) => {
console.log(1); //用于测试执行顺序
str += chunk;
});
// 监听end事件,数据接收完会自动触发
req.on('end', () => {
// 使用querystring模块解析请求体数据,专门用来处理查询字符串。
// 通过这个模块提供的parse()函数,可以将查询字符串解析成对象的格式。
const body = qs.parse(str);
// 解析后将body挂载到req.body属性上
req.body = body;
console.log(2); //用于测试执行顺序
next();
});
// next(); ① //用于标识(下面问题要用)
});
app.post('/save', (req, res) => {
console.log(req.body);
console.log(3); //用于测试执行顺序
res.send('ok');
})
app.listen(8080, () => {
console.log('express server running http://127.0.0.1:8080')
})
上面代码打印结果:
1
2
[Object: null prototype] { name: 'lk', age: '20', gender: '男' }
3
问题:如图所示,next()函数是放在监听data事件中的,为什么不放在①处(监听事件外)?
答:因为req.on监听事件是一个异步函数,如果把next()放在监听事件外面,异步函数还没执行就next(),程序就会先执行后面的路由或中间件了,最后再执行异步任务。这样打印的结果变为
undefined
3
1
2
总结
有问题可以私信或评论。