一、body-parser是什么
Node.js 正文解析中间件。在处理程序之前在中间件中解析传入的请求主体,在req.body
属性下可用。【获取前端数据的插件】
二、body-parser的安装
var bodyParser = require ( 'body-parser' )
三、实例
此示例演示添加通用 JSON 和 URL 编码解析器作为顶级中间件,它将解析所有传入请求的正文。这是最简单的设置。
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))
})
此示例演示了将正文解析器专门添加到需要它们的路由中。一般来说,这是将 body-parser 与 Express 一起使用的最推荐方式。
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) {
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
// create user in req.body
})
所有解析器都接受一个type
选项,该选项允许您更改 Content-Type
中间件将解析的选项。
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// 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' }))