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

不言
풀어 주다: 2018-11-21 11:37:01
앞으로
13510명이 탐색했습니다.

이 글의 내용은 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으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!