模块化之前的代码
index.js
//导入相应的express模块和querystring模块(用来解析请求体数据);
const express = require('express');
const qs = require('querystring');
//创建express的服务器实例
const app = express();
//定义解析表单数据的自定义中间件
app.use(function(req, res, next) {
//定义中间件具体的业务逻辑
//1.定义变量,用来存储客户端发送过来的请求体数据
let str = '';
//2.监听req对象的data事件(客户端发送过来的新的请求体数据)
//使用on来绑定事件
req.on('data', (chunk) => {
//拼接请求体数据,隐式转换为字符串
str += chunk;
})
//3.监听req对象的end事件(请求体发送完毕之后自动触发)
req.on('end', () => {
//打印完整的请求体数据
//console.log(str);
//TODO:把字符串格式的数据解析成对象格式的数据
// 4.使用querystring模块解析请求体数据(前面需要先导入对应的querystring模块)
//调用parse()方法,把查询的字符串解析为对象格式
const body = qs.parse(str);
//5.将解析出来的额请求体对象,挂载为req.body属性
req.body = body;
//最后,一定要调用next()函数,执行后续的业务逻辑
next();
})
});
app.get('/', (req, res) => {
console.log('调用了/这个路由!')
res.send("Home Page!")
})
app.listen(443, () => {
console.log('https:/127.0.0.1')
})
模块化之后的代码
模块化拆分.js
//导入相应的express模块和querystring模块(用来解析请求体数据);
const express = require('express');
//创建express的服务器实例
const app = express();
// 1.导入自己的封装的中间件模块
const customBodyParser = require('./custom-body-parser');
// 2.将自定义的中间函数,注册为全局的中间件
app.use(customBodyParser);
app.get('/', (req, res) => {
console.log('调用了/这个路由!')
res.send("Home Page!")
})
app.listen(443, () => {
console.log('https:/127.0.0.1')
})
custom-body-parser.js
const qs = require('querystring');
const bodyParser = function(req, res, next) {
//定义中间件具体的业务逻辑
//1.定义变量,用来存储客户端发送过来的请求体数据
let str = '';
//2.监听req对象的data事件(客户端发送过来的新的请求体数据)
//使用on来绑定事件
req.on('data', (chunk) => {
//拼接请求体数据,隐式转换为字符串
str += chunk;
})
//3.监听req对象的end事件(请求体发送完毕之后自动触发)
req.on('end', () => {
//打印完整的请求体数据
//console.log(str);
//TODO:把字符串格式的数据解析成对象格式的数据
// 4.使用querystring模块解析请求体数据(前面需要先导入对应的querystring模块)
//调用parse()方法,把查询的字符串解析为对象格式
const body = qs.parse(str);
//5.将解析出来的额请求体对象,挂载为req.body属性
req.body = body;
//最后,一定要调用next()函数,执行后续的业务逻辑
next();
})
}
module.exports = bodyParser;