body-parser 使用详解

一、简介

  • github
  • node.js body 解析中间件
  • 处理程序之前,在中间件中对传入的请求体进行解析(response body)
  • body-parser 提供四种解析器

    JSON body parser
    Raw body parser
    Text body parser
    URL-encoded form body parser

二、使用

搭建一个简单的demo

mkdir body-parser-demo
cd body-parser-demo

npm init -y
npm install express body-parser --save

在根目录下创建index.js

var express = require('express')
var bodyParser = require('body-parser')

const localPort = 3000
var app = express()

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })


app.post('/login.do', (req, res) => {
    console.log('********************')
    console.log(req.body)

    res.end();
})

app.listen(localPort, () => {
    console.log('http://127.0.0.1:%s', host, port)
})

执行node index.js

网络模拟请求使用Postman工具

Postman

不使用中间件,直接获取body

执行结果:

undefined

JSON解析器

app.post('/login.do', jsonParser, (req, res) => {
    console.log('********************')
    console.log(req.body)

    res.end();
})

Postman 以raw 方式发送JSON 数据,执行结果:

{ name: 'wang', password: '123456' }

注:如果在模拟器上以非JSON格式发送,则会获得一个空的JSON对象

urlencoded解析器

app.post('/login.do', urlencodedParser, (req, res) => {
    console.log('********************')
    console.log(req.body)

    res.end();
})

Postman

执行结果:

{ name: 'wang', password: '123456' }

加载到没有挂载路径的中间件

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

具体详见GitHub README.md

注:注意为方便测试,请求处理时直接使用end(),否则会挂起

  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值