[ Web Proxy ]
URL:
Viewing: https://ko.javascript.info/fetch [Back]  [Original]

fetch
:
Light themeDark theme
DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
2020 8 24

fetch

.

.

.

AJAX(Asynchronous JavaScript And XML, JavaScript XML) . AJAX , . AJAX XML .

AJAX .

fetch() . fetch() ( ) .

fetch() .

let promise = fetch(url, [options])
  • url URL
  • options , method header

options GET url .

fetch() . fetch() .

.

, fetch promise Response .

(body) , .

HTTP .

HTTP .

  • status HTTP (: 200)
  • ok . HTTP 200 299 true

:

let response = await fetch(url);

if (response.ok) { // HTTP   200~299 
  //   (   ).
  let json = await response.json();
} else {
  alert("HTTP-Error: " + response.status);
}

.

response . .

  • response.text() ,
  • response.json() JSON ,
  • response.formData() FormData . FormData .
  • response.blob() Blob( ) .
  • response.arrayBuffer() ArrayBuffer( ) .
  • response.body , ReadableStream response.body . .

GitHub JSON .

let url = 'https://api.github.com/repos/javascript-tutorial/ko.javascript.info/commits';
let response = await fetch(url);

let commits = await response.json(); //    JSON  

alert(commits[0].author.login);

await .

fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
  .then(response => response.json())
  .then(commits => alert(commits[0].author.login));

.json() await response.text() .

let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');

let text = await response.text(); //     .

alert(text.slice(0, 80) + '...');

fetch fetch ( ) . Blob .

let response = await fetch('/article/fetch/logo-fetch.svg');

let blob = await response.blob(); //  Blob   .

//  Blob  <img> .
let img = document.createElement('img');
img.;
document.body.append(img);

//   .
img.src = URL.createObjectURL(blob);

setTimeout(() => { // 3   .
  img.remove();
  URL.revokeObjectURL(img.src);
}, 3000);
:

.

response.text() response.json() .

let text = await response.text(); //   .
let parsed = await response.json(); // 

response.headers .

. . .

let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');

//   
alert(response.headers.get('Content-Type')); // application/json; charset=utf-8

//   
for (let [key, value] of response.headers) {
  alert(`${key} = ${value}`);
}

headers fetch . headers .

let response = fetch(protectedUrl, {
  headers: {
    Authentication: 'secret'
  }
});

headers . .

  • Accept-Charset, Accept-Encoding
  • Access-Control-Request-Headers
  • Access-Control-Request-Method
  • Connection
  • Content-Length
  • Cookie, Cookie2
  • Date
  • DNT
  • Expect
  • Host
  • Keep-Alive
  • Origin
  • Referer
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • Via
  • Proxy-*
  • Sec-*

HTTP . , .

POST

GET .

  • method HTTP (: POST)
  • body .
    • (: JSON )
    • FormData form/multipart .
    • Blob BufferSource .
    • URLSearchParams x-www-form-urlencoded , .

JSON .

user .

let user = {
  name: 'John',
  surname: 'Smith'
};

let response = await fetch('/article/fetch/post/user', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(user)
});

let result = await response.json();
alert(result.message);

POST Content-Type text/plain;charset=UTF-8 .

JSON headers Content-Type application/json .

Blob BufferSource fetch .

. <canvas> .

<body style="margin:0">
  <canvas id="canvasElem" width="100" height="80" style="border:1px solid"></canvas>

  <input type="button" value="" onclick="submit()">

  <script>
    canvasElem.onmousemove = function(e) {
      let ctx = canvasElem.getContext('2d');
      ctx.lineTo(e.clientX, e.clientY);
      ctx.stroke();
    };

    async function submit() {
      let blob = await new Promise(resolve => canvasElem.toBlob(resolve, 'image/png'));
      let response = await fetch('/article/fetch/post/image', {
        method: 'POST',
        body: blob
      });

      //         .
      let result = await response.json();
      alert(result.message);
    }

  </script>
</body>

Content-Type . Blob Content-Type . toBlob image/png . Blob Content-Type .

submit() async/await .

function submit() {
  canvasElem.toBlob(function(blob) {
    fetch('/article/fetch/post/image', {
      method: 'POST',
      body: blob
    })
      .then(response => response.json())
      .then(result => alert(JSON.stringify(result, null, 2)))
  }, 'image/png');
}

fetch await .

let response = await fetch(url, options); //    
let result = await response.json(); // json  

await .

fetch(url, options)
  .then(response => response.json())
  .then(result => /*   */)

.

  • response.status HTTP
  • response.ok 200 299 true
  • response.headers HTTP

.

  • response.text()
  • response.json() JSON
  • response.formData() FormData (form/multipart )
  • response.blob() Blob( )
  • response.arrayBuffer() ArrayBuffer( )

fetch .

  • method HTTP
  • headers ( )
  • body ( ) string FormData, BufferSource, Blob, UrlSearchParams

fetch .

GitHub getUsers(names) , GitHub fetch .

GitHub API https://api.github.com/users/ .

.

.

  1. fetch .
  2. .
  3. null .

.

fetch fetch('https://api.github.com/users/') .

200 .json() .

fetch 200 null .

.

async function getUsers(names) {
  let jobs = [];

  for(let name of names) {
    let job = fetch(`https://api.github.com/users/${name}`).then(
      successResponse => {
        if (successResponse.status != 200) {
          return null;
        } else {
          return successResponse.json();
        }
      },
      failResponse => {
        return null;
      }
    );
    jobs.push(job);
  }

  let results = await Promise.all(jobs);

  return results;
}

.then fetch fetch .json() .

await Promise.all(names.map(name => fetch(...))) .json() fetch . fetch .json() fetch JSON .

async-await (Promise) API .

.

.

Web Proxy Viewer  |  New URL  |  Original Page