nodejs http

7/19/2020 nodejs

# 请求概述

  • DNS解析,建立TCP链接,发送http请求
  • server接收到http请求,处理,返回

# 处理http请求

  • get 请求和querystring
  • post请求和postdata
  • 路由
// 简单实例
const http = require('http')
const server = http.createServer((req, res) => {
  res.end('hello world')
})
server.listen(8000)
1
2
3
4
5
6

# 处理get请求

  • get 请求,即客户端要向server端获取数据,如查询列表
  • 通过querystring来传递数据,如 index.html?a=100&b=200
  • 浏览器直接访问,就发送了get请求
const http = require('http')

const querystring = require('querystring')

const server = http.createServer((req, res) => {
  console.log(req.method) // 获取get
  const url = req.url // 获取完整的url 
  req.query = querystring.parse(url.split('?')[1])  // 解析querystring 
  res.end(JSON.stringify(req.query)) // 返回querystring
})

server.listen(8000)
1
2
3
4
5
6
7
8
9
10
11
12

# 处理post 请求

  • post 请求,客户端要向服务端传递数据,如,新建
  • 通过 post data 传递数据,
  • 浏览器无法直接模拟,需要手写ajax, 或者postman
const http = require('http')

// post
const server = http.createServer((req, res) => {
  if (req.method === 'POST') {
    // req 数据格式

    console.log('req context-type: ', req.headers['content-type'])

    // 接收数据
    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })

    req.on('end', () => {
      console.log('postData: ', postData)
      res.end(postData)
    })
  }
})

server.listen(8000)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const http = require('http')
const querystring = require('querystring')

const server = http.createServer((req, res) => {
  const method = req.method
  const url = req.url
  const path = url.split('?')[0]
  const query = querystring.parse(url.split('?')[1])

  // 返回的数据
  const resData = {
    method,
    path,
    url,
    query
  }

  // 设置返回格式 json
  res.setHeader('Content-type', 'application/json')

  // 返回get
  if (method === 'GET') {
    console.log('resData', resData)
    res.end(JSON.stringify(resData))
  }

  // 返回post
  if (method === 'POST') {
    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })



    req.on('end', () => {
      resData.postData = postData
      console.log('resData', resData)
      res.end(JSON.stringify(resData))
    })
  }

})

server.listen(9527)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
更新: 11/2/2022, 11:29:38 PM