JavaScript中的Fetch函數


JavaScript中的Fetch函數

Fetch API提供了一個JavaScript接口,用於訪問和操作Http管道的一些具體的部分,例如請求和響應。還提供一個fetch()方法,該方法提供一種簡單,合理的方式來跨網絡異步獲取資源。

這種功能以前是使用XMLHttpRequest實現的。Fetch挺了一個更理想的替代方案,可以很容易的被其他技術使用。例如Service Workers。Fetch還提供了專門的邏輯空間來定義其他與Http相關的概念,例如Cors和http擴展。

 

注意:fetch規范與Jquery.ajax()主要有三種方式不同:

1.當接收到一個代表錯誤的Http狀態碼時,從fetch()返回的Promise不會被標記為reject,即使響應的http狀態碼時404或500.它將Promise狀態標記為resolve,但是會將resolve的返回值ok屬性設置為false。僅當網絡故障時或者請求被阻止時,才會標記為reject。

2.fetch()不會接受跨域的cookies,也不能使用fetch建立跨域會話,其他網站的set-cookies頭部字段將會被無視。

年tch不會發送cookies,除非使用了credentials的初始化選項。2017年8月25日后,默認的credentials政策更改為same-origin。fixfox在61.0b134版本進行了修改。

示例:

fetch(url)
.then(function(response){return response.json()})
.then(function(myJson){console.log(myJson)})

示例中通過網絡獲取一個json文件並將其打印到控制台。

最簡單的用法只提供一個茶杯上個月用來指明fetch到的資源路徑,然后返回一個包含響應結果的promise(一個Response對象)。

它只是一個Http響應並不是真的JSON,為了獲取JSON的內容,還需要使用json()方法,在Body的mixin中定義,被Request和Response對象實現。

 

帶兩個參數的示例:

// 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'  
})

如果只想在請求URL與調用腳本位於同一起源處時發送憑證,添加credentials:'same-origin'

// The calling script is on the origin 'https://example.com'

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

為確保瀏覽器不在請求中包含憑證,使用omit

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

上傳文件示例:

var formData = new FormData();
var fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

上傳多個文件示例:

var formData = new FormData();
var photos = document.querySelector("input[type='file'][multiple]");

formData.append('title', 'My Vegas Vacation');
// formData 只接受文件、Blob 或字符串,不能直接傳遞數組,所以必須循環嵌入
for (let i = 0; i < photos.files.length; i++) { 
    formData.append('photo', photos.files[i]); 
}

fetch('https://example.com/posts', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

檢測請求是否成功:

如果網絡故障,fetch()promise將會reject戴上一個TypeError對象,雖然這種情況經常遇到權限問題或者是類似問題,如404不是一個網絡故障。想精確的判斷fetch是否成功,需要promise resolved的情況,此時再判斷Response.ok是不是true。

fetch('flowers.jpg').then(function(response) {
  if(response.ok) {
    return response.blob();
  }
  throw new Error('Network response was not ok.');
}).then(function(myBlob) { 
  var objectURL = URL.createObjectURL(myBlob); 
  myImage.src = objectURL; 
}).catch(function(error) {
  console.log('There has been a problem with your fetch operation: ', error.message);
});

自定義請求對象:

除了傳給fetch一個資源的地址,還可以通過Request來構造函數來創建一個request對象,然后再傳給fetch。

var myHeaders = new Headers();

var myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

var myRequest = new Request('flowers.jpg', myInit);

fetch(myRequest).then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage

Request() 和 fetch() 接受同樣的參數。你甚至可以傳入一個已存在的 request 對象來創造一個拷貝:

var anotherRequest = new Request(myRequest,myInit);

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

多維數組或者對象字面量:

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.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]
 
myHeaders.delete("X-Custom-Header");
console.log(myHeaders.getAll("X-Custom-Header")); // [ ]

雖然一些操作只能在 ServiceWorkers 中使用,但是它提供了更方便的操作 Headers 的 API。

如果使用了一個不合法的HTTP Header屬性名,那么Headers的方法通常都拋出 TypeError 異常。如果不小心寫入了一個不可寫的屬性,也會拋出一個 TypeError 異常。除此以外的情況,失敗了並不拋出異常。例如:

var myResponse = Response.error();
try {
  myResponse.headers.set("Origin", "http://mybank.com");
} catch(e) {
  console.log("Cannot pretend to be a bank!");
}

最好在在使用之前檢查內容類型 content-type 是否正確,比如:

fetch(myRequest).then(function(response) {
  if(response.headers.get("content-type") === "application/json") {
    return response.json().then(function(json) {
      // process your JSON further
    });
  } else {
    console.log("Oops, we haven't got JSON!");
  }
});

Guard

由於 Headers 可以在 request 請求中被發送或者在 response 請求中被接收,並且規定了哪些參數是可寫的,Headers 對象有一個特殊的 guard 屬性。這個屬性沒有暴露給 Web,但是它影響到哪些內容可以在 Headers 對象中被操作。

可能的值如下:

  • none:默認的
  • request:從 request 中獲得的 headers(Request.headers)只讀
  • request-no-cors:從不同域(Request.mode no-cors)的 request 中獲得的 headers 只讀
  • response:從 response 中獲得的 headers(Response.headers)只讀
  • immutable:在 ServiceWorkers 中最常用的,所有的 headers 都只讀。

Response 對象

如上所述,Response 實例是在 fetch() 處理完 promise 之后返回的。

你會用到的最常見的 response 屬性有:

  • Response.status — 整數(默認值為200)為response的狀態碼。
  • Response.statusText — 字符串(默認值為"OK"),該值與 HTTP 狀態碼消息對應。
  • Response.ok — 如上所示,該屬性是來檢查response的狀態是否在 200 - 299(包括200 和 299)這個范圍內。該屬性返回一個布爾值

它的實例也可用通過 JavaScript 來創建,但只有在 ServiceWorkers 中才真正有用,當使用 respondWith() 方法並提供了一個自定義的 response 來接受 request 時:

var myBody = new Blob();

addEventListener('fetch', function(event) {
  event.respondWith(new Response(myBody, {
    headers: { "Content-Type" : "text/plain" }
  });
});

Response() 構造方法接受兩個可選參數—— response 的數據體和一個初始化對象(與Request() 所接受的 init 參數類似。)

Body

不管是請求還是響應都能夠包含 body 對象。body 也可以是以下任意類型的實例。

Body 類定義了以下方法(這些方法都被 Request 和Response所實現)以獲取 body 內容。這些方法都會返回一個被解析后的Promise對象和數據。

比起XHR來,這些方法讓非文本化的數據使用起來更加簡單。

請求體可以由傳入 body 參數來進行設置:

var form = new FormData(document.getElementById('login-form'));
fetch("/login", {
  method: "POST",
  body: form
})

特性檢測

Fetch API 的支持情況,可以通過檢測HeadersRequestResponse 或 fetch()是否在Window 或 Worker 域中。例如:

if(self.fetch) {
    // run my fetch request here
} else {
    // do something with XMLHttpRequest?
}

Polyfill

如果要在不支持的瀏覽器中使用 Fetch,可以使用 Fetch Polyfill


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM