body-parse的简单使用

时间:2022-12-19 09:33:03

使用body-parser获取前端传送过来的数据 首先第一步引入

const bodyParser = require('body-parser');
//对body-parser进行配置
app.use( bodyParser.urlencoded({extended: true}) )
//设置完毕之后,会在req对象上面新增一个req.body的一个对象

再来说说node后台对这两种请求格式的处理:

 首先是最新express版本4.7.2:

 4.7.2版本的express没有了bodyParser方法,需要另外安装body-parser模板:于是另外安装了body-parser模板1.5.2版本

使用代码如下:

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());

使用bodyParser.urlencoded(),使node后台支持了第一种请求体.
使用bodyParser.json(),使node后台支持了第二种请求体.

后定义的不会覆盖先定义的… 也就是说,这段代码同时支持了这两种请求体. 另外,虽然请求体的格式不同,但是经过node解析后,他们最终得到的都是json格式的对象.