>  기사  >  웹 프론트엔드  >  JavaScript의 Fetch() 사용 예(코드)

JavaScript의 Fetch() 사용 예(코드)

不言
不言앞으로
2018-11-21 11:37:0113517검색

이 글의 내용은 JavaScript에서 Fetch()의 사용 예제(코드)에 대한 것입니다. 이는 특정 참고 가치가 있으므로 도움이 필요한 친구에게 도움이 되기를 바랍니다.

Fetch()는 네트워크를 통해 리소스를 비동기적으로 요청하는 방법을 제공하며 요청 및 응답과 같은 HTTP 파이프라인의 일부에 액세스하고 작동하는 데 사용됩니다.

가져오기의 일반적인 함정:
  • 오류를 나타내는 HTTP 상태 코드를 수신하면 fetch()에서 반환된 Promise는 거부로 표시되지 않습니다(상태 코드가 404 또는 500인 경우에도). fetch()는 Promise 상태를 해결됨으로 표시합니다(그러나 해결은 값을 반환하지만 OK 속성은 false로 설정됩니다). 네트워크 오류 또는 차단된 요청은 거부된 것으로 표시됩니다.

  • fetch()는 서버에서 쿠키를 보내거나 받지 않습니다. 쿠키를 보내려면 fetch(url, {credentials: 'include'}) 옵션을 설정해야 합니다.

Raw XHR request

var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';

xhr.onload = function() {
  console.log(xhr.response);
};

xhr.onerror = function() {
  console.log("Oops, error");
};

xhr.send();

fetch request

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});

화살표 기능 사용:

fetch(url).then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e))

JSON 파일을 가져와서 콘솔에 인쇄하세요. 리소스 경로를 지정한 다음 응답 객체를 반환하고 json() 메서드를 사용하여 JSON 콘텐츠를 가져옵니다.

fetch 매개변수

fetch()는 다양한 구성의 초기화 매개변수를 제어하기 위해 두 번째 선택적 매개변수를 허용합니다.

// Example POST method implementation:

postData('http://example.com/answer', {answer: 42})
  .then(data => console.log(data)) // JSON from `response.json()` call
  .catch(error => console.error(error))

function postData(url, data) {
  // Default options are marked with *
  return fetch(url, {
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, same-origin, *omit
    headers: {
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    },
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
  })
  .then(response => response.json()) // parses response to JSON
}

자격 증명이 포함된 요청

자격 증명이 포함된 요청:

fetch('https://example.com', {
    //将credentials: 'include'添加到传递给fetch()方法的init对象
    credentials: 'include' 
})

동일한 소스에서 자격 증명을 보내는 경우:

fetch('https://example.com', {
  credentials: 'same-origin'  
})

브라우저가 요청에 자격 증명을 포함하지 않는지 확인하세요.

fetch('https://example.com', {
  credentials: 'omit'  
})

JSON 데이터 업로드

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

파일 업로드

<input type="file" />FormData()fetch()

Headers

Headers 생성자를 사용하여 헤더 개체를 만듭니다. 헤더 개체는 다중 키 값 쌍입니다.

var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");

콘텐츠를 얻을 수 있습니다.

console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false

요약하면 Fetch의 주요 장점은 다음과 같습니다.

    구문이 간결하고 Semantic
  • 표준 Promise를 기반으로 구현되었으며 async/await를 지원합니다
  • isomorphism이 편리하며 isomorphic-fetch
을 사용합니다.

위 내용은 JavaScript의 Fetch() 사용 예(코드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제