Node.js 编写接口入门学习(GET、POST)

一、简介

  • nvm 安装、卸载与使用(详细步骤),用于管理/切换 Node 多版本环境。

  • node 是否安装成功

    $ node -v
    
  • 安装完成之后,通过 node 直接运行 test.js

    // test.js
    console.log('Hello Node')
    
    # 命令行执行
    $ node test.js
    

二、简单的 POSTGET 请求封装

  • test.js

    // http 库
    const http = require('http')
    // 参数解析
    const querystring = require('querystring')
    
    // 创建服务
    const server = http.createServer((req, res) => {
          
          
      // req:请求 res:响应
      // 配置响应数据编码格式
      res.setHeader('Content-Type', 'application/json')
      // 请求方式
      const method = req.method
      // 路由地址
      const url = req.url
      // 拆分成请求路由、请求参数
      const strs = url.split('?')
      // 请求路由
      const path = strs[0]
      // 参数
      const query = querystring.parse(strs[1])
      // 组装成响应数据
      const resData = {
          
          
        method,
        url,
        path,
        query
      }
      // 判断请求类型
      if (method === 'GET') {
          
          
        // 返回响应数据
        res.end(JSON.stringify(resData))
      } else if (method === 'POST') {
          
          
        // 请求数据
        let postData = ''
        // 接收数据流 stream
        req.on('data', chunk => {
          
          
          // chunk 为二进制数据,所以需要转成字符串,而且数据是一点一点传过来的,也自然需要拼接
          postData += chunk.toString()
        })
        // 接收完成
        req.on('end', () => {
          
          
          // 组装数据
          resData.postData = postData
          // 响应数据
          res.end(JSON.stringify(resData))
        })
      } else {
          
          
        res.end('请求方式有误!')
      }
    })
    
    // 监听端口
    // 如果启动报错:Error: listen EADDRINUSE: address already in use :::5000,说明 5000 端口被使用了,换一个端口
    server.listen(8000, () => {
          
          
      console.log('server running at port 8000')
    })
    
    // 运行之后,则可以访问 http://localhost:8000/api/test?id=3
    
  • 请求效果

    iShot_2022-12-20_17.34.08.png

    iShot_2022-12-20_17.34.32.png

三、GET 请求

  • test.js

    // http 库
    const http = require('http')
    // 参数解析
    const querystring = require('querystring')
    
    // 创建服务
    const server = http.createServer((req, res) => {
          
          
      // req:请求 res:响应
      // 获得请求方式
      const method = req.method
      // 请求地址
      const url = req.url
      // 请求参数,传入空也没事
      const query = querystring.parse(url.split('?')[1])
      // 放到请求对象中
      req.query = query
      // 设置响应数据编码格式,这样访问之后就不会出现乱码了
      res.setHeader('Content-Type','text/html; charset=utf-8')
      // 响应数据
      // res.end('Hello Node!并测试中文内容为乱码')
      res.end(JSON.stringify(req.query))
    })
    
    // 监听端口
    // 如果启动报错:Error: listen EADDRINUSE: address already in use :::5000,说明 5000 端口被使用了,换一个端口
    server.listen(8000, () => {
          
          
      console.log('server running at port 8000')
    })
    
    // 运行之后,则可以访问 http://localhost:8000/?id=3
    
  • 挂起服务,然后访问 http://localhost:8000/?id=3

    $ node test.js
    server running at port 8000
    

    iShot_2022-12-20_16.13.54.png

四、POST 请求

  • test.js

    // http 库
    const http = require('http')
    // 参数解析
    const querystring = require('querystring')
    
    // 创建服务
    const server = http.createServer((req, res) => {
          
          
      // req:请求 res:响应
      // 设置响应数据编码格式,这样访问之后就不会出现乱码了
      res.setHeader('Content-Type','text/html; charset=utf-8')
      // 获得请求方式
      const method = req.method
      // 是否为 POST 请求
      if (method === 'POST') {
          
          
        // POST数据
        let postData = ''
        // 接收数据流 stream
        req.on('data', chunk => {
          
          
          // chunk 为二进制数据,所以需要转成字符串,而且数据是一点一点传过来的,也自然需要拼接
          postData += chunk.toString()
        })
        // 接收完成
        req.on('end', () => {
          
          
          // 响应数据
          res.end(postData)
          // res.end({ 'msg': '数据接收完毕', 'data': postData })
        })
      } else {
          
          
        // 其他请求
        res.end('请使用 POST 请求')
      }
    })
    
    // 监听端口
    // 如果启动报错:Error: listen EADDRINUSE: address already in use :::5000,说明 5000 端口被使用了,换一个端口
    server.listen(8000, () => {
          
          
      console.log('server running at port 8000')
    })
    
    // 运行之后,则可以访问 http://localhost:8000/?id=3
    
  • 挂起服务,然后通过 Postman 或 Apifox 访问 http://localhost:8000

    $ node test.js
    server running at port 8000
    

    iShot_2022-12-20_16.47.37.png

猜你喜欢

转载自blog.csdn.net/zz00008888/article/details/128388059