# fetch
# 1. 介绍
一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。
用于替代 XMLHttpRequest
# 2. 使用
# 2.1. 基本使用
fetch("http://example.com/movies.json")
.then((response) => response.json())
.then((data) => console.log(data));
# 2.2. 常用请求参数
async function postData(url = "", data = {}) {
const response = await fetch(url, {
// GET, POST, PUT, DELETE, etc.
method: "POST",
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
// body data type must match "Content-Type" header
body: JSON.stringify(data),
// 关闭页面时,请求不会被强制取消
// 用于页面卸载时(window.onunload) 发送请求
keepalive: true,
});
// parses JSON response into native JavaScript objects
return response.json();
}
postData("https://example.com/answer", { answer: 42 })
.then((data) => {
console.log(data); // JSON data parsed by `data.json()` call
});
# 2.3. 上传文件
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);
});
# 2.4. 上传多个文件
const formData = new FormData();
const photos = document.querySelector('input[type="file"][multiple]');
formData.append("title", "My Vegas Vacation");
for (let i = 0; i < photos.files.length; i++) {
formData.append(`photos_${i}`, photos.files[i]);
}
fetch("https://example.com/posts", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
# 2.5. 请求图片
const image = document.querySelector(".my-image");
fetch("flowers.jpg")
.then(function (response) {
return response.blob();
})
.then(function (blob) {
const objectURL = URL.createObjectURL(blob);
image.src = objectURL;
});
# 2.6. Response 对象
说明:
fetch("flowers.jpg").then(response: Response) => {...})
常用属性:
- Response.headers : 关联的 Headers 对象。
- Response.ok : 布尔值,标示该 Response 成功(HTTP 状态码的范围在 200-299)
- Response.status : 状态码(例如 200 表示成功)
- Response.statusText : 状态信息(例如,OK 对应 200)
- Response.url : URL
常用方法:(Response 实现了 Body 接口)
- Body.blob() : 返回一个被解析为 Blob 格式的 Promise 对象
- Body.formData()
- Body.json()
- Body.text()
# 3. 参考
上一篇: 下一篇:
本章目录