• Ajax
  • Ant design
  • Axios-Fetch
  • Avue
  • Browser
  • Canvas
  • CSS
  • Dos-bat
  • Dva
  • Dedecms
  • Echart
  • ElementUI
  • Editors
  • Git
  • GeoServer
  • GIS
  • H5
  • Jquery
  • Java安卓
  • Json
  • Javascript
  • Leaflet
  • Linux
  • Life-Info
  • Mock
  • MongoDB
  • Network
  • NodeJS
  • NPM
  • React
  • 设计运营
  • SEO
  • SVG
  • TypeScript
  • Tools
  • umi
  • uni-APP
  • Vant
  • Vue
  • Windows
  • webpack
  • 位置:OC中文网 > 其他 > NodeJS >

    Express中间件body-parser

    来源:openlayers-cesium.com 时间:02-18

     body-parser是一个HTTP请求体解析的中间件,使用这个模块可以解析JSON、Raw、文本、URL-encoded格式的请求体

    1. /* 引入依赖项 */ 
    2. var express = require('express'); 
    3. // …… 
    4. var bodyParser = require('body-parser'); 
    5.  
    6. var routes = require('./routes/index'); 
    7. var users = require('./routes/users'); 
    8.  
    9. var app = express(); 
    10.  
    11. // …… 
    12.  
    13. // 解析 application/json 
    14. app.use(bodyParser.json());  
    15. // 解析 application/x-www-form-urlencoded 
    16. app.use(bodyParser.urlencoded()); 
    在上述代码中,模块会处理application/x-www-form-urlencoded、application/json两种格式的请求体。经过这个中间件后,就可以在所有路由处理器的req.body中访问请求参数

    不同的解析

    在实际项目中,不同路径可能要求用户使用不同的内容类型,body-parser还支持为单个express路由添加请求体解析。
    1. var express = require('express'); 
    2. var bodyParser = require('body-parser'); 
    3.  
    4. var app = new express(); 
    5.  
    6. //创建application/json解析 
    7. var jsonParser = bodyParser.json(); 
    8.  
    9. //创建application/x-www-form-urlencoded 
    10. var urlencodedParser = bodyParser.urlencoded({extended: false}); 
    11.  
    12. //POST /login 中获取URL编码的请求体 
    13. app.post('/login', urlencodedParser, function(req, res){ 
    14.     if(!req.body) return res.sendStatus(400); 
    15.     res.send('welcome, ' + req.body.username); 
    16. }) 
    17.  
    18. //POST /api/users 获取JSON编码的请求体 
    19. app.post('/api/users', jsonParser, function(req,res){ 
    20.     if(!req.body) return res.sendStatus(400); 
    21.     //create user in req.body 
    22. }) 

    非标准请求头中的解析

    1. // 解析自定义的 JSON 
    2. app.use(bodyParser.json({ type: 'application/*+json' })) 
    3.  
    4. // 解析自定义的 Buffer 
    5. app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) 
    6.  
    7. // 将 HTML 请求体做为字符串处理 
    8. app.use(bodyParser.text({ type: 'text/html' })) 
    当请求体解析之后,解析值会被放到req.body属性中,当内容为空时候,为一个空对象{}
    ---bodyParser.json()--解析JSON格式
    ---bodyParser.raw()--解析二进制格式
    ---bodyParser.text()--解析文本格式
    ---bodyParser.urlencoded()--解析文本格式