body-parser中间件
1.什么是body-parser
用来解析http请求体,就是接受post请求的参数使用的中间件
2.下载
终端下 cnpm i -D body-parser
3.导入(引用)
const bodyParser = require('body-parser') ;
4.作用
- application/x-www-form-urlencoded 常见的form提交
使用方法:app.use(bodyParser.urlencoded({extended:false}));
bodyParser.urlencoded模块用于解析req.body的数据,解析成功后覆盖原来的req.body.如果解析失败则为{}。该模块有一个属性extended,默认值为true,但是已经是不赞成的了,使用的时候是false
- application/json 提交json格式的数据
使用方法:app.use(bodyParser.json());
- multipart/form-data 文件提交
- ext/xml 提交xml格式的数据
5.使用的格式
写在总路由中
//1.导入模块
//1.1 express
const express = require('express');
//1.2 body-parser
const bodyParser = require('body-parser');
//2.实例化对象
let app = express();
//3.使用中间件
//3.1 解析表单格式的参数
app.use(bodyParser.urlencoded({extended:false}));
//3.2 解析json格式的参数
app.use(bodyParser.json());
//4.监听端口
app.listen(8000,()=>{
console.log('web server ok,baseURL:'http://localhost:8000';
}