近日在使用express的时候,发现中间件 body-parser,无法正确解析,
无法解析的代码如下:
app.use(bodyParser.urlencoded({ extended: true }))
且无论是用 bodyParser.json() 还是 bodyParser.raw()都无法解析出来
无可奈何,自己写了个 中间函数解析 raw形式的json,代码如下:
app.use((req,res,next)=>{
let chunk = ''
req.on('data',(data)=>{chunk+=data})
req.on('end',()=>{
try{
req.chunk = JSON.parse(chunk)
}catch(err){
req.chunk = chunk
console.log(err)
}
next()
})
})
执行该中间函数,会解析raw里的json,并且写入到req.chunk里面,然后next完会在其他函数里访问到。
我可能写了个不规范的中间件╮(╯▽╰)╭