当前位置: 首页 » 产品 » 商务广告 » 正文

node.js中express中间件body-parser如何使用

放大字体  缩小字体 发布日期: 2024-09-22 15:34   来源:http://www.baidu.com/  作者:无忧资讯  浏览次数:14
核心提示:我是在学习nodejs时候,对着书本的例子时,使用bodyParser这个中间件,在终端运行出问题,报错大概意思也是express4.0中没有body

我是在学习nodejs时候,对着书本的例子时,使用bodyParser这个中间件,在终端运行出问题,报错大概意思也是express4.0中没有bodyParser这个内置中间件了,还给了body-parser的GitHub源代码地址:https://github.com/expressjs/body-parser.

经过看源代码下面的说明知道了body-parser的三种用法:

在讲用法之间,我们需要弄清楚下面四个不同的处理方法:这四个处理方法分别对body的内容采用不同的处理方法;分别是处理json数据、Buffer流数据、文本数据、UTF-8的编码的数据。

bodyParser.json(options) 、bodyParser.raw(options) 、bodyParser.text(options) 、bodyParser.urlencoded(options)

以下是它的三种用法:

1、底层中间件用法:这将拦截和解析所有的请求;也即这种用法是全局的。

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: ') res.end(JSON.stringify(req.body, null, 2)) })

express的use方法调用body-parser实例;且use方法没有设置路由路径;这样的body-parser实例就会对该app所有的请求进行拦截和解析。

2、特定路由下的中间件用法:这种用法是针对特定路由下的特定请求的,只有请求该路由时,中间件才会拦截和解析该请求;也即这种用法是局部的;也是最常用的一个方式。

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

express的post(或者get)方法调用body-parser实例;且该方法有设置路由路径;这样的body-parser实例就会对该post(或者get)的请求进行拦截和解析。

3、设置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' }));

 
 
[ 产品搜索 ]  [ 加入收藏 ]  [ 告诉好友 ]  [ 打印本文 ]  [ 违规举报 ]  [ 关闭窗口 ]

 

 
    行业协会  备案信息  可信网站