body-parser 使用详解
来源:直接复制网 时间:09-22
在http请求种,POST、PUT、PATCH三种请求方法中包含着请求体,也就是所谓的request,在Nodejs原生的http模块中,请求体是要基于流的方式来接受和解析。
body-parser是一个HTTP请求体解析的中间件,使用这个模块可以解析JSON、Raw、文本、URL-encoded格式的请求体,
原生:
- const http = require('http');
- http.createServer(function(req, res){
- if(req.method.toLowerCase() === 'post'){
- let body = '';
- //此步骤为接收数据
- req.on('data', function(chunk){
- body += chunk;
- });
- //开始解析
- req.on('end', function(){
- if(req.headers['content-type'].indexOf('application/json')!==-1){
- JSON.parse(body);
- }else if(req.headers['content-type'].indexOf('application/octet-stream')!==-1){
- //Rwa格式请求体解析
- }else if(req.headers['content-type'].indexOf('text/plain')!==-1){
- //text文本格式请求体解析
- }else if(req.headers['content-type'].indexOf('application/x-www-form-urlencoded')!==-1){
- //url-encoded格式请求体解析
- }else{
- //其他格式解析
- }
- })
- }else{
- res.end('其他方式提交')
- }
- }).listen(3000)
Express框架默认使用body-parser作为请求体解析中间件,在创建了Express项目之后,可以在app.js文件中找到
- /* 引入依赖项 */
- var express = require('express');
- // ……
- var bodyParser = require('body-parser');
- var routes = require('./routes/index');
- var users = require('./routes/users');
- var app = express();
- // ……
- // 解析 application/json
- app.use(bodyParser.json());
- // 解析 application/x-www-form-urlencoded
- app.use(bodyParser.urlencoded());
---bodyParser.json()--解析JSON格式
---bodyParser.raw()--解析二进制格式
---bodyParser.text()--解析文本格式
---bodyParser.urlencoded()--解析文本格式