node JS 处理 http 请求之 GET 和 POST 请求

一、http

  1. http 请求概述,如下所示:
  • DNS 解析,建立 TCP 连接,发送 http 请求
  • server 接收到 http 请求,处理,并返回
  • 客户端接收到返回数据,处理数据,如渲染页面,执行 JS
  1. node JS 处理 http 请求,如下所示:
  • get 请求和 querystring
  • post 请求和 postdata
  • 路由

二、node JS 处理 get 请求

  1. node JS 处理 get 请求,如下所示:
  • get 请求,即客户端要向 server 端获取数据,如查询列表
  • 通过 querystring 来传递数据,如 a.html?a=100&b=200
  • 浏览器直接访问,就发送 get 请求
  1. 通过 npm init -y 初始化项目,新建 app.js 文件,代码如下所示:
const http = require('http')
const querystring = require('querystring')

const server = http.createServer((req, res) => {
    
    
  console.log('method:', req.method)
  const url = req.url
  console.log('url:', url)
  req.query = querystring.parse(url.split('?')[1])
  console.log('query:',req.query)
  res.end(JSON.stringify(req.query)) 
})

server.listen(8000)
console.log('ok')
  1. 通过 node app.js 命令运行项目,在浏览器窗口分别输入 http://localhost:8000/api/listhttp://localhost:8000/api/list?name=zhangsan&age=20, 发送 GET 请求,如下所示:
  • http://localhost:8000/api/list,如图所示:

在这里插入图片描述
在这里插入图片描述

  • http://localhost:8000/api/list?name=zhangsan&age=20,如图所示:

在这里插入图片描述
在这里插入图片描述

三、node JS 处理 post 请求

  1. node JS 处理 post 请求,如下所示:
  • post 请求,即客户端要像服务端传递数据,如新建信息
  • 通过 post.data 传递数据
  • 浏览器无法直接模拟,需要手写 js,或者使用 postman
  1. app.js 文件中,代码如下所示:
const http = require('http')
const querystring = require('querystring')

const server = http.createServer((req,res) => {
    
    
  if (req.method === 'POST') {
    
    
    // req 数据格式
    console.log('req content-type:', req.headers['content-type'])
    // 接收数据
    let postData = ''
    req.on('data', chunk => {
    
    
      postData += chunk.toString()
    })
    req.on('end', () => {
    
    
      console.log('postData:', postData)
      res.end('end 结束')
    })
  }
})


server.listen(8000)
console.log('ok')
  1. 通过 node app.js 命令运行项目,在 postman 中,在 http://localhost:8000/ 请求中,在 raw 中输入 { "name": "zhangsan", "age": 24 },发送 POST 请求,如下图所示:

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42614080/article/details/110734309