← 返回完整题库
Node.js困难

body-parser 这个中间件是做什么用的?

参考答案

作用

body-parser 是 Express 的请求体解析中间件:把请求流读取出来,按 Content-Type 解析成 JS 对象,挂到 **req.body** 上。在此之前 req.body 是 undefined。

支持的解析器

  • bodyParser.json():解析 application/json,可配 limit、strict、reviver。
  • bodyParser.urlencoded({ extended }):解析表单 application/x-www-form-urlencoded,extended: true 用 qs 支持嵌套对象,false 用 querystring 只支持平铺。
  • bodyParser.text():按纯文本读入,req.body 是字符串。
  • bodyParser.raw():读成 Buffer,常用于支付回调验签。

为什么不用它

Express 4.16+ 已内置 express.json() / express.urlencoded(),底层就是 body-parser,新项目不必单独安装。

注意点

  • 只处理匹配的 Content-Type,其他类型会跳过(req.body 仍为空)。
  • 一定要设 limit(如 10mb),否则大请求体会打爆内存。
  • 文件上传(multipart/form-data)不能用它,要用 multer / busboy。
  • 解析失败会抛出带 status=400 的错误,需要错误中间件处理。

本题来自 计算机知识面试题库,共 921 道题。