Fetch API 提供了一個 JavaScript 接口,用於訪問和操縱 HTTP 管道的一些具體部分,例如請求和響應。它還提供了一個全局
fetch()
方法,該方法提供了一種簡單,合理的方式來跨網絡異步獲取資源。這種功能以前是使用
XMLHttpRequest
實現的。Fetch 提供了一個更理想的替代方案,可以很容易地被其他技術使用,例如Service Workers
。Fetch 還提供了專門的邏輯空間來定義其他與 HTTP 相關的概念,例如 CORS 和 HTTP 的擴展。
使用 Fetch 封裝的 GET 和 POST 請求:
import 'whatwg-fetch';
// 統一對 get 方法進行封裝
export const get = async (url, data = {}) => {
try {
// 拼接 get 請求參數
let query = '';
Object.entries(data).forEach(([key, value], index) => {
query = query + index === 0 ? '?' : '&';
query += `${key}=${value}`;
});
// 發送異步請求
const response = await fetch(`${url}${query}`);
const res = await response.json();
return res;
} catch (error) {
alert("GET 請求失敗!");
console.log(error);
}
};
// 統一對 post 方法進行封裝
export const post = async (url, data = {}) => {
try {
const response = await fetch(url, {
method: 'POST', // 默認爲 GET 請求
body: JSON.stringify(data)
});
const res = await response.json();
return res;
} catch (error) {
alert("POST 請求失敗!");
console.log(error);
}
};
使用方法:
const data = await post('/api/register', {
username,
tel,
password,
repassword
});
console.log(data);