| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch | [Back] [Original] |
Get to know MDN better
This page was translated from English by the community. Learn more and join the MDN Web Docs community.
Fetch API HTTP JavaScript . Fetch API fetch() .
API XMLHttpRequest , Fetch API . Fetch API CORS HTTP .
.
async function logJSONData() {
const response = await fetch("http://example.com/movies.json");
const jsonData = await response.json();
console.log(jsonData);
}
JSON . fetch() . Response , JSON .
Response JSON . Response HTTP , JSON json() . json() JSON , .
, Content-Security-Policy connect-src .
fetch() . , init .
fetch() , .
// POST
async function postData(url = "", data = {}) {
// *
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE
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 "Content-Type"
});
return response.json(); // JSON JavaScript
}
postData("https://example.com/answer", { answer: 42 }).then((data) => {
console.log(data); // JSON `data.json()`
});
mode: "no-cors" .
AcceptAccept-LanguageContent-LanguageContent-Type, application/x-www-form-urlencoded, multipart/form-data, text/plain fetch() AbortController AbortSignal .
const controller = new AbortController();
const signal = controller.signal;
const url = "video.mp4";
const downloadBtn = document.querySelector("#download");
const abortBtn = document.querySelector("#abort");
downloadBtn.addEventListener("click", async () => {
try {
const response = await fetch(url, { signal });
console.log(" ", response);
} catch (error) {
console.error(` : ${error.message}`);
}
});
abortBtn.addEventListener("click", () => {
controller.abort();
console.log(" ");
});
fetch() init credential: 'include' . .
fetch("https://example.com", {
credentials: "include",
});
:
credentials: 'include' , Access-Control-Allow-Origin . . CORS .
: , . CORS .
URL credentials: 'same-origin' .
// 'https://example.com'
fetch("https://example.com", {
credentials: "same-origin",
});
credentials: 'omit' .
fetch("https://example.com", {
credentials: "omit",
});
fetch() JSON POST .
async function postJSON(data) {
try {
const response = await fetch("https://example.com/profile", {
method: "POST", // 'PUT'
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const result = await response.json();
console.log(":", result);
} catch (error) {
console.error(":", error);
}
}
const data = { username: "example" };
postJSON(data);
fetch() <input type="file"> , FormData() .
async function upload(formData) {
try {
const response = await fetch("https://example.com/profile/avatar", {
method: "PUT",
body: formData,
});
const result = await response.json();
console.log(":", result);
} catch (error) {
console.error(":", error);
}
}
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append("username", "abc123");
formData.append("avatar", fileField.files[0]);
upload(formData);
fetch() <input type="file" multiple> , FormData() .
async function uploadMultiple(formData) {
try {
const response = await fetch("https://example.com/posts", {
method: "POST",
body: formData,
});
const result = await response.json();
console.log(":", result);
} catch (error) {
console.error(":", error);
}
}
const photos = document.querySelector('input[type="file"][multiple]');
const formData = new FormData();
formData.append("title", "My Vegas Vacation");
for (const [i, photo] of Array.from(photos.files).entries()) {
formData.append(`photos_${i}`, photo);
}
uploadMultiple(formData);
, Uint8Array. , '' . . ( UTF-8 , .)
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) {
//
yield chunk.substr(startIndex);
}
}
async function run() {
for await (let line of makeTextFileLineIterator(urlOfFile)) {
processLine(line);
}
}
run();
fetch() , CORS TypeError . , 404 . fetch() , Response.ok true .
async function fetchImage() {
try {
const response = await fetch("flowers.jpg");
if (!response.ok) {
throw new Error(" OK ");
}
const myBlob = await response.blob();
myImage.src = URL.createObjectURL(myBlob);
} catch (error) {
console.error(" :", error);
}
}
fetch() , Request() .
async function fetchImage(request) {
try {
const response = await fetch(request);
if (!response.ok) {
throw new Error(" OK ");
}
const myBlob = await response.blob();
myImage.src = URL.createObjectURL(myBlob);
} catch (error) {
console.error(":", error);
}
}
const myHeaders = new Headers();
const myRequest = new Request("flowers.jpg", {
method: "GET",
headers: myHeaders,
mode: "cors",
cache: "default",
});
fetchImage(myRequest);
Request() fetch() . .
const anotherRequest = new Request(myRequest, myInit);
. , / init . .
:
clone() . , . .
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");
2 .
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
Headers HTTP TypeError . ( ) TypeError . . .
const myResponse = Response.error();
try {
myResponse.headers.set("Origin", "http://mybank.com");
} catch (e) {
console.log(" !");
}
. .
async function fetchJSON(request) {
try {
const response = await fetch(request);
const contentType = response.headers.get("content-type");
if (!contentType || !contentType.includes("application/json")) {
throw new TypeError(", JSON !");
}
const jsonData = await response.json();
//
} catch (error) {
console.error(":", error);
}
}
, ''(guard) . , .
.
none: .request: (Request.headers) .request-no-cors: Request.mode no-cors .response: (Response.headers) .immutable: . . :
Content-Length . ,Set-Cookie . , .
Response fetch() .
.
Response.status . 200.Response.statusText . . HTTP/2 .Response.ok , 200 299 . JavaScript , respondWith() .
const myBody = new Blob();
addEventListener("fetch", function (event) {
// fetch ServiceWorker
event.respondWith(
new Response(myBody, {
headers: { "Content-Type": "text/plain" },
}),
);
});
Response() . , Request() .
:
error() . , redirect() URL . .
. .
ArrayBufferTypedArray (Uint8Array )DataViewBlobFileString URLSearchParamsFormDataRequest.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,
});
, fetch() . , Content-Type .
Fetch API Window Worker Headers, Request, Response, fetch() .
if (window.fetch) {
// fetch
} else {
// XMLHttpRequest ?
}
This page was last modified on 2025 10 10 by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |