首頁  >  文章  >  web前端  >  JavaScript中Fetch() 的用法範例(程式碼)

JavaScript中Fetch() 的用法範例(程式碼)

不言
不言轉載
2018-11-21 11:37:0113373瀏覽

這篇文章帶給大家的內容是關於JavaScript中Fetch() 的用法範例(程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

Fetch()提供了一種方式進行跨網路非同步請求資源的方式,用於存取和操作HTTP管道的部分,例如:請求和對應。

fetch常見的坑:
  • 接收到表示錯誤的HTTP狀態碼時,fetch()傳回的Promise不會被標記為reject(即使狀態碼為404或500)。 fetch()會將Promise狀態標記為resolve(但resolve傳回值但OK 屬性設為 false)。網路故障或請求被阻止才會標記為reject。

  • fetch()不會從服務端發送或接收任何cookies。發送cookies 需要設定 fetch(url, {credentials: 'include'}) 選項。

原始XHR請求

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請求

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文件,並列印到控制台。指明資源路徑,然後傳回一個Response對象,使用json()方法取得JSON但內容。

fetch參數

fetch()接受第二個可選參數,控制不同配置的init參數。

// 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));

上傳檔案

使用 FormData()fetch()

Headers

使用Headers建構子建立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 優點主要有:

  • 語法簡潔,更語意化

  • ##基於標準Promise 實現,支援async/await

  • 同構方便,使用isomorphic-fetch

以上是JavaScript中Fetch() 的用法範例(程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除