欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

搭建json-server服务器和封装axios

程序员文章站 2022-05-20 09:26:30
...

首先通过json-server搭建一个服务器,在全局安装npm i -g json-server
然后新建一个文件名为db.json,在文件中写一些json数据,
最后通过 json-server --watch .\db.json 启动服务器,这样简单的服务器就搭建好了
接下来通过对axios请求的封装并进行测试

封装一个简单的axios
function axios({ method, url, data, params }) {
      return new Promise((resolve, reject) => {
        method = method.toUpperCase()
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              const response = {
                request: url,
                status: xhr.status,
                data: JSON.parse(xhr.responseText)
              }
              resolve(response)
            } else {
              reject("error")
            }
          }
        }

        let qs = ""
        if (params) {
          qs = Object.keys(params).reduce((p, key) => {
            return p + `${key}=${value}&`
          }, "?").slice(0, -1)
        }
        xhr.open(method, url + qs)
        let body = ''
        if ((method == 'POST' || method == 'PUT' || method == 'PATCH') && data) {
          xhr.setRequestHeader('content-type', 'application/json')
          body = JSON.stringify(data)
        }
        xhr.send(body)
      })
    }
测试代码
<button id="box1">按钮1</button>
<button id="box2">按钮2</button>
document.getElementById("box1").onclick = function () {
      axios({
        method: "GET",
        url: "http://localhost:3000/commtents",
      }).then((value) => {
        console.log("value", value.data)
      }).catch((reason) => {
        console.log("reason", reason)
      })
    }
    document.getElementById("box2").onclick = function () {
      axios({
        method: "POST",
        url: "http://localhost:3000/commtents",
        data: {
          "body": "eight",
          "postId": 2
        }
      }).then((value) => {
        console.log("value", value.data)
      }).catch((reason) => {
        console.log("reason", reason)
      })
    }