// 封装一个 body-parser 中间件
// 定义一个函数
// 引入querystring模块
let querystring = require('querystring')
// 拿到post请求的参数
// let bodyParser = ()=>{
// return (req,res,next)=>{
// let str = ''
// req.on('data',chunk=>str+=chunk)
// req.on('end',()=>{
// req.body = querystring.parse(str)
// })
// next() //让后续的请求代码执行
// }
// }
//设置请求的最大数据量
// 使用 app.use(bodyParser({limit:10}))
// let bodyParser = (options)=>{
// options = options || {}
// options.limit = options.limit || 102400 //设置请求的最大数据量
// return (req,res,next)=>{
// let str = ''
// req.on('data',chunk=>str+=chunk)
// req.on('end',()=>{
// // req.body = querystring.parse(str)
// if(str.length > options.limit){
// throw new Error()
// }else{
// req.body = querystring.parse(str)
// console.log('中间件',req.body)
// }
// next() //让后续的请求代码执行
// })
// }
// }
// 返回一个函数
// module.exports = bodyParser
// 使用 app.use(bodyParser.urlencoded({limit:10}))
module.exports = {
urlencoded: (options) => {
options = options || {}
options.limit = options.limit || 102400 //设置请求的最大数据量
return (req, res, next) => {
let str = ''
req.on('data', chunk => str += chunk)
req.on('end', () => {
if (str.length > options.limit) {
throw new Error()
} else {
req.body = querystring.parse(str)
console.log('中间件', req.body)
}
next() //让后续的请求代码执行
})
}
}
}
03-31