2

基于 Web 的前后端数据传输

 1 year ago
source link: https://s.ourai.ws/notes/data-transmission-in-web-based-apps/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

XMLHttpRequest(XHR)

Fetch

与 XHR 不同的是,fetch() 会返回一个 Promise,更加符合现代前端的异步编程模型:

<!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" />

    <title>Fetch basic example</title>

    <link rel="stylesheet" href="" />
  </head>

  <body>
    <h1>Fetch basic example</h1>

    <img src="" class="my-image" />
  </body>
  <script>
    const myImage = document.querySelector(".my-image");

    fetch("flowers.jpg")
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP error, status = ${response.status}`);
        }
        return response.blob();
      })
      .then((myBlob) => {
        const objectURL = URL.createObjectURL(myBlob);
        myImage.src = objectURL;
      })
      .catch((error) => {
        const p = document.createElement("p");
        p.appendChild(document.createTextNode(`Error: ${error.message}`));
        document.body.insertBefore(p, myImage);
      });
  </script>
</html>

fetch() 刚被支持时,已经发出去且尚未完成的请求是无法被取消的,但在 2017、2018 年时各大浏览器陆续支持通过第二个参数传入 signal 中止请求:

let controller;
const url = "video.mp4";

const downloadBtn = document.querySelector(".download");
const abortBtn = document.querySelector(".abort");

downloadBtn.addEventListener("click", fetchVideo);

abortBtn.addEventListener("click", () => {
  if (controller) {
    controller.abort();
    console.log("Download aborted");
  }
});

function fetchVideo() {
  controller = new AbortController();
  const signal = controller.signal;
  fetch(url, { signal })
    .then((response) => {
      console.log("Download complete", response);
    })
    .catch((err) => {
      console.error(`Download error: ${err.message}`);
    });
}

WebSocket

Web Workers


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK