JS - 获取 API

1. 获取API(然后/捕获)

Fetch 用于发出 HTTP 请求(API 调用)。它返回一个 Promise。

基本流程:

1
fetch → Promise → then → then → catch

示例 1:简单的 GET 请求

1
2
3
4
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));

示例 2:处理响应状态

1
2
3
4
5
6
7
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(res => {
if(!res.ok) throw new Error("Request failed");
return res.json();
})
.then(data => console.log(data))
.catch(err => console.log("Error:",err.message));

示例 3:POST 请求

1
2
3
4
5
6
7
8
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello" })
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));

示例 4:链接多个 then

1
2
3
4
5
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(res => res.json())
.then(user => user.id)
.then(id => console.log("User id:", id))
.catch(err => console.log(err));

示例 5:等效的 async/await

async function loadUser(){
  try{
    const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
    const data = await res.json();
    console.log(data);
  }catch(err){
    console.log(err);
  }
}
loadUser();