Express 中间件body-parser

邹祺
2023-12-01

1.body-parser是什么?
body-parser是一个HTTP请求体解析中间件,使用这个模块可以解析JSON、Raw、文本、URL-encoded格式的请求体,Express框架中就是使用这个模块做为请求体解析中间件。
body-parser模块是一个Express中间件,它使用非常简单且功能强大
2.下载配置body-parser

npm install body-parser

3.基本使用

var express = require('express')
//获取模块
var bodyParser = require('body-parser')

var app = express()

// 创建 application/json 解析
var jsonParser = bodyParser.json()

// 创建 application/x-www-form-urlencoded 解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login 获取 URL编码的请求体
app.post('/login', urlencodedParser, function (req, res) {
 
})

// POST /api/users 获取 JSON 编码的请求体
app.post('/api/users', jsonParser, function (req, res) {

});
app.listen(3000);

对请求体的四种解析方式

1\. bodyParser.json(options): 解析json数据
2\. bodyParser.raw(options): 解析二进制格式(Buffer流数据)
3\. bodyParser.text(options): 解析文本数据
4\. bodyParser.urlencoded(options): 解析UTF-8的编码的数据。

bodyParser变量是对中间件的引用。请求体解析后,解析值都会被放到req.body属性,内容为空时是一个{}空对象。

 类似资料: