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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡尔特斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值