使用fetch请求接口的完整步骤

380 阅读1分钟

使用的接口 const url = "https://v2.alapi.cn/api/qinghua";

fetch不需要像axios那样引入,fetch里面有2个参数,一个是url,一个是参数配置

语法fetch().then().then().catch(),第一个then()是一个箭头函数,先获取到数据。第二个then()里面的箭头函数作用是把获取到的数据打印出来。

fetch 官方文档: https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API

写的比较好的参考文档(阮大师):https://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html

我们使用的在线接口文档: https://www.alapi.cn/api/view/98

完整代码如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>每天一句土味情话</h1>
    <p></p>
  </body>
  <script>
    // 获取到的数据最后要渲染到p标签里面
    const p = document.querySelector("p");
    const url = "https://v2.alapi.cn/api/qinghua";
    // fetch不需要像axios那样引入,
    // fetch里面有2个参数,一个是url,一个是参数配置
    fetch(url, {
        // 开始参数配置,请求方法是(method:POST)
      method: "POST",
      //   传递参数时候的格式,以什么方式发送请求的参数
      headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
      },
      //   设置token和返回时候的格式
      body: "token=Od57Mf5oIUHyW8Eu&format=json",
    })
      // 第一个then先获取到数据
      .then((response) => {
        return response.json();
      })

      // 第二个then把返回得到到的数据打印出来
      //   1秒只能执行一次,测试的时候不要频繁更新
      .then((json) => {
        // 到第二个then可以打印一下返回的是什么,然后从里面把我们想要的拿出来
        // 然后添加到p标签里面
        console.log(json);
        p.innerHTML = json.data.content;
      })
      //   如果有错,比如接口地址写错,就返回错误
      //   箭头函数的完整写法是需要return的,但是使用console.log,就不用加return 了,直接打印
      .catch((err) => console.log("Request Failed", err));
  </script>
</html>