body-parser小解

时间:2023-03-10 01:55:28
body-parser小解

body-parser用来解析http请求体,对不同的content-type有不同的处理方式,

首先介绍一下常见的四种Content-Type:

1.application/x-www-form-urllencodes form表单提交

2.application/json 提交json格式的数据

3.text/xml 提交xml格式的数据

4.multipart/form-data 文件提交

body-parser对body也有四种处理方式:

1.bodyParser.urlencoded(options)

2.bodyParser.json(options)

3.bodyParser.text(options)

4.bodyParser.raw(options)

解析实质: 解析原有的req.body,解析成功后用解析结果覆盖原有的req.body,解析失败则为{}

urlencoded小解

常见的使用方法为bodyParser.urlencoded({extened: false})

解析: querystring是node内建的对象,用来字符串化对象或解析字符串,qs为一个querystring库,在其基础上添加更多的功能和安全性,

extened为true时表示再额外加上qs,一般不需要

常见用法:

1、底层中间件用法:这将拦截和解析所有的请求;也即这种用法是全局的。

var express = require('express')
var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false })) // parse application/json
app.use(bodyParser.json()) app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})

express的use方法调用body-parser实例;且use方法没有设置路由路径;这样的body-parser实例就会对该app所有的请求进行拦截和解析。

2、特定路由下的中间件用法:这种用法是针对特定路由下的特定请求的,只有请求该路由时,中间件才会拦截和解析该请求;也即这种用法是局部的;也是最常用的一个方式

var express = require('express')
var bodyParser = require('body-parser') var app = express() // create application/json parser
var jsonParser = bodyParser.json() // create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false }) // POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
}) // POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
// create user in req.body
})

3、设置Content-Type 属性;用于修改和设定中间件解析的body类容类型。

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }); // parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })); // parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));