body-parser小解

body-parser用來解析http請求體,對不一樣的content-type有不一樣的處理方式,html

首先介紹一下常見的四種Content-Type:node

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

2.application/json 提交json格式的數據json

3.text/xml 提交xml格式的數據api

4.multipart/form-data 文件提交 安全

 

body-parser對body也有四種處理方式:app

1.bodyParser.urlencoded(options)post

2.bodyParser.json(options)ui

3.bodyParser.text(options)url

4.bodyParser.raw(options)

 

解析實質: 解析原有的req.body,解析成功後用解析結果覆蓋原有的req.body,解析失敗則爲{}

 

urlencoded小解

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

解析: querystring是node內建的對象,用來字符串化對象或解析字符串,qs爲一個querystring庫,在其基礎上添加更多的功能和安全性,

extened爲true時表示再額外加上qs,通常不須要

 

常見用法:

一、底層中間件用法:這將攔截和解析全部的請求;也即這種用法是全局的。

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全部的請求進行攔截和解析。

二、特定路由下的中間件用法:這種用法是針對特定路由下的特定請求的,只有請求該路由時,中間件纔會攔截和解析該請求;也即這種用法是局部的;也是最經常使用的一個方式

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
})

三、設置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' }));
相關文章
相關標籤/搜索