使用 Fetch

  • 它還提供了一個全局 fetch()方法
  • 這種功能之前是使用 XMLHttpRequest實現的。Fetch提供了一個更好的替代方法,能夠很容易地被其餘技術使用,例如 Service Workers。
  • Fetch還提供了單個邏輯位置來定義其餘HTTP相關概念,例如CORS和HTTP的擴展。?
  • 兩種方式的不一樣
    • 當接收到一個表明錯誤的 HTTP 狀態碼時,從 fetch()返回的 Promise 不會被標記爲 reject, 即便該 HTTP 響應的狀態碼是 404 或 500。相反,它會將 Promise 狀態標記爲 resolve (可是會將 resolve 的返回值的 ok 屬性設置爲 false ),僅當網絡故障時或請求被阻止時,纔會標記爲 reject。
    • 默認狀況下,fetch 不會從服務端發送或接收任何 cookies, 若是站點依賴於用戶 session,則會致使未經認證的請求(要發送 cookies,必須設置 credentials 選項)。

進行 fetch 請求

  • 響應是一個 Response 對象。爲了獲取JSON的內容,咱們須要使用 json()方法(在Bodymixin 中定義,被 Request 和 Response 對象實現)。
fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json(); // response.json()返回promise
  })
  .then(function(myJson) {
    console.log(myJson);
  });
  • 最好使用符合內容安全策略 (CSP)的連接而不是使用直接指向資源地址的方式來進行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
}

發送帶憑據的請求

  • 讓瀏覽器發送包含憑據的請求(即便是跨域源),要將credentials: 'include'添加到傳遞給 fetch()方法的init對象。
fetch('https://example.com', {
  credentials: 'include'  
})
  • 請求URL與調用腳本位於同一塊兒源處時發送憑據,請添加credentials: 'same-origin'。
// The calling script is on the origin 'https://example.com'(調用腳原本源於https://example.com)

fetch('https://example.com', {
  credentials: 'same-origin'  
})
  • 確保瀏覽器不在請求中包含憑據,請使用credentials: 'omit'。
fetch('https://example.com', {
  credentials: 'omit'  
})

上傳 JSON 數據

  • 使用 fetch() POST 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));

上傳文件

  • 能夠經過HTML元素,FormData() 和fetch()上傳文件。
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));

檢測請求是否成功

  • 若是遇到網絡故障,fetch() promise 將會 reject,帶上一個 TypeError 對象。
  • 想要精確的判斷 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);
});

自定義請求對象

  • 能夠經過使用 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.src = objectURL;
});
  • Request() 和 fetch() 接受一樣的參數。你甚至能夠傳入一個已存在的 request 對象來創造一個拷貝:
  • 由於 request 和 response bodies 只能被使用一次(譯者注:這裏的意思是由於設計成了 stream (流)的方式,因此它們只能被讀取一次)。建立一個拷貝就能夠再次使用 request/response 了,固然也可使用不一樣的 init 參數。?
  • clone() 方法也能夠用於建立一個拷貝。它在語義上有一點不一樣於其餘拷貝的方法。其餘方法(好比拷貝一個 response)中,若是 request 的 body 已經被讀取過,那麼將執行失敗,然而 clone() 則不會失敗。?
var anotherRequest = new Request(myRequest,myInit);

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");
  • 能夠傳一個多維數組或者對象字面量:
myHeaders = new Headers({
  "Content-Type": "text/plain",
  "Content-Length": content.length.toString(),
  "X-Custom-Header": "ProcessThisImmediately",
});
  • 它的內容能夠被獲取:(增、刪、查、改)
  • 一些操做只能在 ServiceWorkers 中使用?
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")); // [ ]
  • 若是使用了一個不合法的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 對象有一個特殊的 guard 屬性。這個屬性沒有暴露給 Web,可是它影響到哪些內容能夠在 Headers 對象中被操做。(在 ServiceWorkers 中使用?)
  • 可能值以下 ?
    • none:默認的
    • request:從 request 中得到的 headers(Request.headers)只讀(不能夠修改或添加請求頭,全部的?)
    • request-no-cors:從不一樣域(Request.mode no-cors)的 request 中得到的 headers 只讀
    • response:從 response 中得到的 headers(Response.headers)只讀
    • immutable:在 ServiceWorkers 中最經常使用的,全部的 headers 都只讀。(ServiceWorkers 是不能給合成的 Response 的 headers 添加一些 cookies)

Response 對象

  • Response 實例是在 fetch() 處理完promises以後返回的
  • 最多見的response屬性有:
    • Response.status — 整數(默認值爲200) 爲response的狀態碼.
    • Response.statusText — 字符串(默認值爲"OK"),該值與HTTP狀態碼消息對應.
    • Response.ok — 如上所示, 該屬性是來檢查response的狀態是否在200-299(包括200,299)這個範圍內.該屬性返回一個Boolean值.
  • 它的實例也可用經過 JavaScript 來建立, 但只有在ServiceWorkers中才真正有用,當使用respondWith()方法並提供了一個自定義的response來接受request時:
  • Response() 構造方法接受兩個可選參數—response的數據體和一個初始化對象(與Request()所接受的init參數相似.)
// ServiceWorkers 中
var myBody = new Blob();

addEventListener('fetch', function(event) {
  event.respondWith(new Response(myBody, {
    headers: { "Content-Type" : "text/plain" }
  });
});
  • 靜態方法error()只是返回了一個錯誤的response.Service Workers纔有。
  • redirect() 返回了一個能夠重定向至某URL的response.Service Workers纔有。

Body

  • 不論是請求仍是響應都可以包含body對象. body也能夠是如下任意類型的實例.
    • ArrayBuffer 二進制數據緩衝區
    • ArrayBufferView (Uint8Array等) // ArrayBufferView 沒有特定的實體,是指一類二進制數據對象,叫類數組數據
    • Blob/File
    • string
    • URLSearchParams(URL搜索參數)
    • FormData
  • Body 類定義瞭如下方法 (這些方法都被 Request 和Response所實現)以獲取body內容
  • 這些方法都會返回一個被解析後的Promise對象和數據.
    • arrayBuffer()
    • blob()
    • json()
    • text()
    • formData()
  • 請求體能夠由傳入body參數來進行設置:
var form = new FormData(document.getElementById('login-form'));
fetch("/login", {
  method: "POST",
  body: form
})
  • request和response(包括fetch() 方法)都會試着自動設置Content-Type。若是沒有設置Content-Type值,發送的請求也會自動設值。

特性檢測

  • Fetch API 的支持狀況,能夠經過檢測Headers, Request, Response 或 fetch()是否在Window 或 Worker 域中(對象是否包含這個屬性或方法)
if(self.fetch) {
    // run my fetch request here
} else {
    // do something with XMLHttpRequest?
}

Polyfill

  • 要在不支持的瀏覽器中使用Fetch,可使用Fetch Polyfill。
相關文章
相關標籤/搜索