项目作者: penghuwan

项目描述 :
Promise风格的bodyparser,接收request对象做为参数,返回解析后的body对象,返回结果前做了charset转换,解压缩,内容编码转换等处理
高级语言: JavaScript
项目地址: git://github.com/penghuwan/body-parser-promise.git
创建时间: 2019-08-16T08:41:49Z
项目社区:https://github.com/penghuwan/body-parser-promise

开源协议:

下载




个人知乎专栏文章

bodyparser实现原理解析
包含对代码设计的详细注解

body-parser-promise

Promise风格的bodyparser,接收request对象做为参数,返回解析后的body对象,返回结果前做了charset转换,解压缩,内容编码转换等处理

Usage

  1. 安装依赖
    1. npm i body-parser-promise
  2. 使用
    ```js
    const getRequestBody = require(‘body-parser-promise’)

http.createServer(async (req,res) => {
// 如果Content-Type为application/www-form-urlencode或者application/json,则body是解析后的对象
// 如果Content-Type为text/plain,则body是一个字符串
// 具体的内容输出参考下面的demo
const body = await getRequestBody(req, res);
})

  1. # Demo
  2. 如果你想看看这个demo是怎么运作的,你可以
  3. 1. clone项目
  4. ```git
  5. git clone https://github.com/penghuwan/body-parser-promise.git
  1. 安装相关依赖
    1. npm install
  2. 启动Node客户端和Node服务端
    1. node client.js // Node.js客户端,向server发送gzip压缩后的消息
    2. node server.js // Node.js服务端,负责解析每个请求的request.body,并输出
  3. 在浏览器端刷新localhost:3000页面
  4. 最后你可在server.js的进程控制台中看到输出:
    1. // 来自client.js客户端发送的压缩body
    2. 我是一个被Gzip压缩后的数据
    3. // 来自前端请求,连续三次fetch的body
    4. {
    5. data: '我是彭湖湾',
    6. contentType: 'application/json',
    7. charset: 'gbk'
    8. }
    9. {
    10. data: '我是彭湖湾',
    11. contentType: 'application/x-www-form-urlencoded',
    12. charset: 'UTF-8'
    13. }
    14. 我是彭湖湾,这句话采用UTF-8格式编码,content-typetext/plain