5/15-API接口调用,增删改查——CRUD工程师养成记

219 阅读2分钟

这节课的主要内容,就是学会查看接口文档,并根据接口文档来操纵数据!

前情回顾

image.png

// 创建一个 XMLHttpRequest 对象 
let xhr = new XMLHttpRequest(); 
// 输出 XMLHttpRequest 对象的 readyState 值
console.log(xhr.readyState);//0
// 设置请求方式和请求地址 
xhr.open("get", "./10-json.json"); 
// 发送请求 xhr.send(); 
// 输出 XMLHttpRequest 对象的 readyState 值 
console.log(xhr.readyState);//1 
// 监听 XMLHttpRequest 对象的状态变化
xhr.onreadystatechange = function () {
// 输出 XMLHttpRequest 对象的 readyState 值 
console.log(xhr.readyState);//2,3,4 
//当 readyState 值为 4 (即请求已完成)时,输出从服务端返回的数据(json格式) 
if (xhr.readyState === 4) { console.log(JSON.parse(this.responseText)); } };

查看所有的图书

image.png

写法的话,get和post方法略有区别

btn1.onclick = function () {
          let xhr = new XMLHttpRequest();
          xhr.open("get", "http://cxk520.top:3000/books/queryall");
          xhr.send();
          xhr.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200)
              console.log(JSON.parse(this.responseText));
          };
        };

注册用户

image.png

let xhr = new XMLHttpRequest();
          xhr.open("post", "http://cxk520.top:3000/users/register");

          xhr.setRequestHeader(
            "Content-Type",
            "application/x-www-form-urlencoded"
          );

          xhr.send(`username=${u}&userpwd=${p}`);
          xhr.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
              console.log(JSON.parse(this.responseText));
              let { message, status } = JSON.parse(this.responseText);
              if (status === 201) {
                alert(message);
                // location.href='./login.html'
              } else {
                alert("注册失败!");
              }
            }
          };

get/post区别

目前据我观察,写法上的区别是:

  • post写法必须带上请求头 xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
  • post传递的参数写在send()中,而get则是先写?再写传递的参数

而GPT给出的解释是:

Get和Post是HTTP协议中常用的两种请求方式,二者有以下异同点:

相同点:

  • 都是向服务器发送HTTP请求;
  • 都需要发送请求头和请求体;
  • 都可以通过URL参数传递数据;

不同点:

  • 请求方式:Get请求是通过URL直接发送请求,Post请求是通过请求体发送请求;
  • 数据类型:Get请求只能发送简单的键值对数据,而Post请求可以发送各种格式的数据,如json、xml等;
  • 数据长度:Get请求会受到浏览器地址栏长度的限制,一般不能超过2000个字符;而Post请求则没有这个限制;
  • 安全性:Post请求相对于Get请求更加安全,因为Post请求的请求体不会被暴露在URL中,可以避免敏感数据的泄露;
  • 缓存:Get请求可以被浏览器缓存,Post请求不能被浏览器缓存;

总的来说,Get请求适合传递少量数据,而Post请求适合传递大量数据或者敏感数据。

demo 利用头条API来渲染页面

<!--
 * @Author: Ray123
 * @Description: 
 * @Date: 2023-05-15 19:04:20
 * @LastEditTime: 2023-05-15 19:48:08
 * @FilePath: \0515\头条api试用.html
-->
<!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>
    <script>
      window.onload = function () {
        let xhr = new XMLHttpRequest();
        xhr.open("post", "https://apis.tianapi.com/toutiaohot/index");
        xhr.setRequestHeader(
          "Content-Type",
          "application/x-www-form-urlencoded"
        );

        xhr.send(`key=这里填写你自己的key哦`);

        xhr.onreadystatechange = function () {
          if (this.readyState == 4 && this.status == 200) {
            let data = JSON.parse(this.responseText);
            console.log(data.result.list);
            data.result.list.forEach((item, index) => {
              let newTr = document.createElement("tr");
              newTr.innerHTML = `
                <tr>
                <th>${index + 1}</th>
                <th>${item.word}</th>
                <th>${item.hotindex}</th>
            </tr>
                `;
              list.appendChild(newTr);
            });
          }
        };
      };
    </script>
  </head>
  <body>
    <table width="600" border="1" cellspacing="0" cellpadding="0">
      <thead>
        <tr>
          <th>编号</th>
          <th>热搜</th>
          <th>热度</th>
        </tr>
      </thead>
      <tbody id="list">
        <!-- <tr>
                <th></th>
                <th></th>
                <th></th>
            </tr> -->
      </tbody>
    </table>
  </body>
</html>

最终效果:

image.png