Skip to content

Express教程03:自己实现一个body-parser中间件 #70

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
chencl1986 opened this issue Apr 26, 2019 · 0 comments
Open

Express教程03:自己实现一个body-parser中间件 #70

chencl1986 opened this issue Apr 26, 2019 · 0 comments

Comments

@chencl1986
Copy link
Owner

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

中间件的实现逻辑

我们在使用body-parser时的用法如下:

server.use(bodyParser.json())

这个方法等价于:

server.use((req, res, next) => {
  // 处理数据代码。
  ...

  // 处理完成后,交由下一级中间件处理。
  next()
})

也就是说,bodyParser.json()方法的返回值是一个处理数据的函数。

新建中间件

新建一个中间件的js文件在/lesson03/libs/body-parser.js

该模块导出了一个处理数据的方法:

示例代码:/lesson03/libs/body-parser.js

module.exports = (req, res, next) => {
  // 处理数据代码。
  ...

  // 处理完成后,交由下一级中间件处理。
  next()
}

实现中间件代码

由于Express传入的req参数中,还保留了原生node.js的属性和方法,因此可以使用data事件接收post传入的数据。

const querystring = require('querystring')

module.exports = (req, res, next) => {
  let arr = []  // 接收数据的数组

  // 使用data事件接收数据
  req.on('data', (buffer) => {
    // 将数据保存在arr数组中
    arr.push(buffer)
  })

  // 数据接收完成后,将数据转换为对象格式,保存到req.body上,交由下一级中间件处理
  req.on('end', () => {
    // 将数据解析为字符串
    let body = Buffer.concat(arr).toString()

    // 判断是否Fetch请求数据
    if (req.headers['content-type'] === 'application/json') {
      // 处理Fetch请求数据
      body = JSON.parse(body)
    } else {
      // 处理表单提交数据
      body = querystring.parse(body)
    }

    // 将保存到req.body上
    req.body = body

    // 交由下一级中间件处理
    next()
  })
}

使用中间件

接下来,只要将bodyParser中间件引入,然后使用server.use(bodyParser)即可。

示例代码:/lesson03/server.js

const express = require('express')

// 引入bodyParser中间件
const bodyParser = require('./libs/body-parser')

const server = express()

server.listen(8080)

server.get('/reg', (req, res, next) => {
  console.log(req.query)
  res.send({
    error: 0,
    data: req.query,
    msg: '注册成功'
  })
})

// 使用bodyParser中间件
server.use(bodyParser)

server.post('/login', (req, res, next) => {
  console.log(req.body)
  res.send({
    error: 0,
    data: req.body,
    msg: '登陆成功'
  })
})

server.use(express.static('./static/'))

console.log(`Server started at 8080`)

启动服务器后,访问http://localhost:8080/index.html即可看到效果。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant