| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch | [Back] [Original] |
Get to know MDN better
Fetch API JavaScript HTTP fetch()
XMLHttpRequest Fetch Service WorkersFetch HTTP CORS HTTP
fetch jQuery.ajax()
fetch() Promise reject HTTP 404 500 Promise resolve HTTP 200 - 299 resolve ok false rejectfetch cookie credentials 2018 8 credentials same-originFirefox 61.0b13 fetch
fetch("http://example.com/movies.json")
.then((response) => response.json())
.then((data) => console.log(data));
JSON fetch() promise Response
HTTP JSON JSON json() body JSON promise
(CSP) fetch
fetch() init
// Example POST method implementation:
async function postData(url = "", data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data), // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData("https://example.com/answer", { answer: 42 }).then((data) => {
console.log(data); // JSON data parsed by `data.json()` call
});
mode: "no-cors" HTTP
AcceptAccept-LanguageContent-LanguageContent-Type application/x-www-form-urlencodedmultipart/form-data text/plain credentials: 'include' fetch() init
fetch("https://example.com", {
credentials: "include",
});
credentials: 'include' Access-Control-Allow-Origin "*"Access-Control-Allow-Origin CORS Unblock
URL credentials: 'same-origin'
// The calling script is on the origin 'https://example.com'
fetch("https://example.com", {
credentials: "same-origin",
});
credentials: 'omit'
fetch("https://example.com", {
credentials: "omit",
});
fetch() POST JSON
const data = { username: "example" };
fetch("https://example.com/profile", {
method: "POST", // or 'PUT'
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
console.log("Success:", data);
})
.catch((error) => {
console.error("Error:", error);
});
HTML <input type="file" /> FormData() fetch()
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);
});
HTML <input type="file" multiple /> FormData() fetch()
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);
});
Uint8Array fetch() UTF-8 fetch()
async function* makeTextFileLineIterator(fileURL) {
const utf8Decoder = new TextDecoder("utf-8");
const response = await fetch(fileURL);
const reader = response.body.getReader();
let { value: chunk, done: readerDone } = await reader.read();
chunk = chunk ? utf8Decoder.decode(chunk) : "";
const re = /\n|\r|\r\n/gm;
let startIndex = 0;
let result;
for (;;) {
let result = re.exec(chunk);
if (!result) {
if (readerDone) {
break;
}
let remainder = chunk.substr(startIndex);
({ value: chunk, done: readerDone } = await reader.read());
chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
startIndex = re.lastIndex = 0;
continue;
}
yield chunk.substring(startIndex, result.index);
startIndex = re.lastIndex;
}
if (startIndex < chunk.length) {
// last line didn't end in a newline char
yield chunk.substr(startIndex);
}
}
async function run() {
for await (let line of makeTextFileLineIterator(urlOfFile)) {
processLine(line);
}
}
run();
CORS fetch() promise reject TypeError 404 fetch() promise resolved Response.ok true
fetch("flowers.jpg")
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not OK");
}
return response.blob();
})
.then((myBlob) => {
myImage.src = URL.createObjectURL(myBlob);
})
.catch((error) => {
console.error("There has been a problem with your fetch operation:", error);
});
fetch() Request() request fetch()
const myHeaders = new Headers();
const myRequest = new Request("flowers.jpg", {
method: "GET",
headers: myHeaders,
mode: "cors",
cache: "default",
});
fetch(myRequest)
.then((response) => response.blob())
.then((myBlob) => {
myImage.src = URL.createObjectURL(myBlob);
});
Request() fetch() request
const anotherRequest = new Request(myRequest, myInit);
request response bodies stream request/response init body body body
clone() request response body clone() body body
Headers Headers() headers headers
const content = "Hello World";
const myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
const myHeaders = new Headers({
"Content-Type": "text/plain",
"Content-Length": content.length.toString(),
"X-Custom-Header": "ProcessThisImmediately",
});
console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue");
console.log(myHeaders.get("Content-Length")); // 11
console.log(myHeaders.get("X-Custom-Header")); // ['ProcessThisImmediately', 'AnotherValue']
myHeaders.delete("X-Custom-Header");
console.log(myHeaders.get("X-Custom-Header")); // null
ServiceWorkers Headers API
HTTP Header Headers TypeError TypeError
const myResponse = Response.error();
try {
myResponse.headers.set("Origin", "http://mybank.com");
} catch (e) {
console.log("Cannot pretend to be a bank!");
}
content-type
fetch(myRequest)
.then((response) => {
const contentType = response.headers.get("content-type");
if (!contentType || !contentType.includes("application/json")) {
throw new TypeError("Oops, we haven't got JSON!");
}
return response.json();
})
.then((data) => {
/* process your data further */
})
.catch((error) => console.error(error));
Headers request response Headers guard Web Headers
nonerequest request headersRequest.headersrequest-no-corsRequest.mode no-cors request headers response response headersResponse.headersimmutable ServiceWorkers headers guard request Request Header Content-Length Set-Cookie response header Service Worker Response cookie
Response fetch() promise
response
Response.status 200 response Response.statusText "" HTTP HTTP/2 Response.ok response 200 - 299 200 299 JavaScript ServiceWorkers respondWith() response request
const myBody = new Blob();
addEventListener("fetch", (event) => {
// ServiceWorker intercepting a fetch
event.respondWith(
new Response(myBody, {
headers: { "Content-Type": "text/plain" },
}),
);
});
Response() response body Request() init
error() responseredirect() URL response Service Worker
body body
ArrayBufferTypedArray (Uint8Array )Blob/FileURLSearchParamsFormDataBody Request Response body Promise
Request.arrayBuffer() / Response.arrayBuffer()Request.blob() / Response.blob()Request.formData() / Response.formData()Request.json() / Response.json()Request.text() / Response.text()XHR
body
const form = new FormData(document.getElementById("login-form"));
fetch("/login", {
method: "POST",
body: form,
});
request response fetch() Content-Type Content-Type
Fetch API Headers, Request, Response fetch() Window Worker
if (window.fetch) {
// run my fetch request here
} else {
// do something with XMLHttpRequest?
}
| Web Proxy Viewer | New URL | Original Page |