经常使用APIexpress
1. bodyParser.text(options) 解析文本格式json
返回一个仅处理字符串格式处理的中间件。其后的全部的req.body中将会是一个字符串值。api
1. defaultCharset - 若是Content-Type后没有指定编码时,使用此编码。默认为'utf-8'app 2. inflate - 设置为true时,deflate压缩数据会被解压缩;设置为true时,deflate压缩数据会被拒绝。默认为true。函数 3. limit - 设置请求的最大数据量。默认为'100kb'post 4. type - 该选项用于设置为指定MIME类型的数据使用当前解析中间件。这个选项能够是一个函数或是字符串,当是字符串是会使用type-is来查找MIMI类型;当为函数是,中间件会经过fn(req)来获取实际值。默认为application/octet-stream。大数据 5. verify - 这个选项仅在verify(req, res, buf, encoding)时受支持ui |
2. bodyParser.urlencoded(options) 解析UTF-8的编码的数据。返回一个处理urlencoded数据的中间件。编码
option可选值url
1. extended - 当设置为false时,会使用querystring库解析URL编码的数据;当设置为true时,会使用qs库解析URL编码的数据。后没有指定编码时,使用此编码。默认为true 2. inflate - 设置为true时,deflate压缩数据会被解压缩;设置为true时,deflate压缩数据会被拒绝。默认为true。 3. limit - 设置请求的最大数据量。默认为'100kb' 4. parameterLimit - 用于设置URL编码值的最大数据。默认为1000 5. type - 该选项用于设置为指定MIME类型的数据使用当前解析中间件。这个选项能够是一个函数或是字符串,当是字符串是会使用type-is来查找MIMI类型;当为函数是,中间件会经过fn(req)来获取实际值。默认为application/octet-stream。 6. verify - 这个选项仅在verify(req, res, buf, encoding)时受支持 |
代码示例:
var express = require('express') varbodyParser = require('body-parser') var app = express()
// create application/json parser varjsonParser = bodyParser.json() // create application/x-www-form-urlencoded parser varurlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /home 获取 urlencoded bodies app.post('/home', urlencodedParser, function (req, res) { if (!req.body) return res.sendStatus(400) res.send('welcome, ' + req.body.username) })
// POST /api/users 获取 JSON bodies app.post('/about', jsonParser, function (req, res) { if (!req.body) return res.sendStatus(400) res.send('welcome ****, ' + req.body.username) });
app.listen(3000); |
图片一
图片二