1 简介
参考文件:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
2 使用
基本用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| async function postData(url = "", data = {}) { const response = await fetch(url, { method: "POST", mode: "cors", cache: "no-cache", credentials: "same-origin", headers: { "Content-Type": "application/json", }, redirect: "follow", referrerPolicy: "no-referrer", body: JSON.stringify(data), }); return response.json(); }
postData("https://example.com/answer", { answer: 42 }).then((data) => { console.log(data); });
|
上传文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const formData = new FormData(); const fileField = document.querySelector('input[type="file"]');
formData.append("username", "abc123"); formData.append("avatar", fileField.files[0]);
fetch("https://example.com/profile/avatar", { method: "PUT", body: formData, }) .then((response) => response.json()) .then((result) => { console.log("Success:", result); }) .catch((error) => { console.error("Error:", error); });
|