Skip to content
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

Nodejs教程08:同时处理GET、POST请求 #39

Open
chencl1986 opened this issue Mar 18, 2019 · 1 comment
Open

Nodejs教程08:同时处理GET、POST请求 #39

chencl1986 opened this issue Mar 18, 2019 · 1 comment

Comments

@chencl1986
Copy link
Owner

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

同时处理GET/POST请求

通常在开发过程中,同一台服务器需要接收多种类型的请求,并区分不同接口,向客户端返回数据。

最常用的方式,就是对请求的方法、url进行区分判断,获取到每个请求的数据后,统一由一个回调函数进行处理。

如下示例代码,可以在/lesson08/form_get.html和/lesson08/form_post.html中,通过提交表单查看效果。

示例代码:/lesson08/server.js

const http = require('http')
const url = require('url')
const querystring = require('querystring')

const server = http.createServer((req, res) => {
  // 定义公共变量,存储请求方法、路径、数据
  const method = req.method
  let path = ''
  let get = {}
  let post = {}

  // 判断请求方法为GET还是POST,区分处理数据
  if (method === 'GET') {
    // 使用url.parse解析get数据
    const { pathname, query } = url.parse(req.url, true)

    path = pathname
    get = query

    complete()
  } else if (method === 'POST') {
    path = req.url
    let arr = []

    req.on('data', (buffer) => {
      // 获取POST请求的Buffer数据
      arr.push(buffer)
    })

    req.on('end', () => {
      // 将Buffer数据合并
      let buffer = Buffer.concat(arr)

      // 处理接收到的POST数据
      post = querystring.parse(buffer.toString())

      complete()
    })
  }

  // 在回调函数中统一处理解析后的数据
  function complete() {
    console.log(method, path, get, post)
  }
})

server.listen(8080)
@q23wwwwe
Copy link

demo代码中JSON.parse报错 应改为querystring.parse吧?

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

2 participants