Express中间件body-parser
来源:openlayers-cesium.com 时间:02-18
body-parser是一个HTTP请求体解析的中间件,使用这个模块可以解析JSON、Raw、文本、URL-encoded格式的请求体
- /* 引入依赖项 */
- var express = require('express');
- // ……
var bodyParser = require('body-parser'); - var routes = require('./routes/index');
- var users = require('./routes/users');
- var app = express();
- // ……
// 解析 application/json app.use(bodyParser.json()); // 解析 application/x-www-form-urlencoded app.use(bodyParser.urlencoded());
在上述代码中,模块会处理application/x-www-form-urlencoded、application/json两种格式的请求体。经过这个中间件后,就可以在所有路由处理器的req.body中访问请求参数
不同的解析
在实际项目中,不同路径可能要求用户使用不同的内容类型,body-parser还支持为单个express路由添加请求体解析。
- var express = require('express');
- var bodyParser = require('body-parser');
- var app = new 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){- if(!req.body) return res.sendStatus(400);
- res.send('welcome, ' + req.body.username);
- })
- //POST /api/users 获取JSON编码的请求体
- app.post('/api/users',
jsonParser, function(req,res){- if(!req.body) return res.sendStatus(400);
- //create user in req.body
- })
非标准请求头中的解析
- // 解析自定义的 JSON
- app.use(bodyParser.json({ type: 'application/*+json' }))
- // 解析自定义的 Buffer
- app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
- // 将 HTML 请求体做为字符串处理
- app.use(bodyParser.text({ type: 'text/html' }))
当请求体解析之后,解析值会被放到req.body属性中,当内容为空时候,为一个空对象{}
---bodyParser.json()--解析JSON格式
---bodyParser.raw()--解析二进制格式
---bodyParser.text()--解析文本格式
---bodyParser.urlencoded()--解析文本格式
---bodyParser.json()--解析JSON格式
---bodyParser.raw()--解析二进制格式
---bodyParser.text()--解析文本格式
---bodyParser.urlencoded()--解析文本格式