1. 程式人生 > >React開發中使用fetch進行異步請求

React開發中使用fetch進行異步請求

React fetch 異步

React開發中使用fetch進行異步請求

最新的Web API接口中提供了一個全局fetch方法,從而以一種更為簡單、合理的方式來支持跨網絡異步獲取資源。

這種功能以前是使用 XMLHttpRequest實現的。Fetch提供了一個更好的替代方法,可以很容易地被其他技術使用,例如 Service Workers。Fetch還提供了單個邏輯位置來定義其他HTTP相關概念,例如CORS和HTTP的擴展。

請註意,fetch規範與jQuery.ajax()主要有兩種方式的不同:

  • 當接收到一個代表錯誤的 HTTP 狀態碼時,從 fetch()返回的 Promise 不會被標記為 reject, 即使該 HTTP 響應的狀態碼是 404 或 500。相反,它會將 Promise 狀態標記為 resolve (但是會將 resolve 的返回值的 ok 屬性設置為 false ),僅當網絡故障時或請求被阻止時,才會標記為 reject。
  • 默認情況下,fetch 不會從服務端發送或接收任何 cookies, 如果站點依賴於用戶 session,則會導致未經認證的請求(要發送 cookies,必須設置 credentials 選項)。

基本的fetch請求舉例

一個基本的 fetch請求設置起來很簡單。看看下面的代碼:

fetch(‘http://example.com/movies.json‘)
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

這裏我們通過網絡獲取一個JSON文件並將其打印到控制臺。最簡單的用法是只提供一個參數用來指明想fetch()到的資源路徑,然後返回一個包含響應結果的promise(一個 Response 對象)。

第二個可選參數

fetch() 接受第二個可選參數,一個可以控制不同配置的 init 對象:

參考 fetch(),查看所有可選的配置和更多描述。

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

上傳文件

在最新瀏覽器API編程中,你可以使用一個HTML <input type="file" /> 輸入元素,並結合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 對象。雖然這個情況經常是遇到了權限問題或類似問題——比如 404 不是一個網絡故障。想要精確的判斷 fetch() 是否成功,需要包含 promise解析的情況,此時再判斷 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.src = objectURL;
});

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


var anotherRequest = new Request(myRequest,myInit);

這個很有用,因為 request 和 response bodies 只能被使用一次(譯者註:這裏的意思是因為設計成了 stream 的方式,所以它們只能被讀取一次)。創建一個拷貝就可以再次使用 request/response 了,當然也可以使用不同的 init 參數。

React開發中使用fetch

要在不支持的瀏覽器中使用Fetch,可以使用Fetch Polypill(https://github.com/github/fetch)。

上面示例中使用了 fetch API。它是替代 XMLHttpRequest 用來發送網絡請求的非常新的 API。由於目前大多數瀏覽器原生還不支持它,React開發中建議你使用 cross_fetch 庫(https://github.com/lquixada/cross-fetch):

// 每次使用 `fetch` 前都這樣調用一下
import fetch from ‘cross_fetch‘

在底層,它在瀏覽器端使用 whatwg-fetch polyfill,在服務器端使用 node-fetch,所以如果當你把應用改成 同構 時,並不需要改變 API 請求。

註意,fetch polyfill 假設你已經使用了 Promise 的 polyfill。確保你使用 Promise polyfill 的一個最簡單的辦法是在所有應用代碼前啟用 Babel 的 ES6 polyfill:

// 在應用中其它任何代碼執行前調用一次
import ‘babel-polyfill‘

一個相對完整的使用fetch的例子

import fetch from ‘cross-fetch‘

export const REQUEST_POSTS = ‘REQUEST_POSTS‘
function requestPosts(subreddit) {
return {
type: REQUEST_POSTS,
subreddit
}
}

export const RECEIVE_POSTS = ‘RECEIVE_POSTS‘
function receivePosts(subreddit, json) {
return {
type: RECEIVE_POSTS,
subreddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
}
}

export const INVALIDATE_SUBREDDIT = ‘INVALIDATE_SUBREDDIT’
export function invalidateSubreddit(subreddit) {
return {
type: INVALIDATE_SUBREDDIT,
subreddit
}
}

// 來看一下我們寫的第一個 thunk action 創建函數!
// 雖然內部操作不同,你可以像其它 action 創建函數 一樣使用它:
// store.dispatch(fetchPosts(‘reactjs‘))

export function fetchPosts(subreddit) {

// Thunk middleware 知道如何處理函數。
// 這裏把 dispatch 方法通過參數的形式傳給函數,
// 以此來讓它自己也能 dispatch action。

return function (dispatch) {

// 首次 dispatch:更新應用的 state 來通知
// API 請求發起了。

dispatch(requestPosts(subreddit))

// thunk middleware 調用的函數可以有返回值,
// 它會被當作 dispatch 方法的返回值傳遞。

// 這個案例中,我們返回一個等待處理的 promise。
// 這並不是 redux middleware 所必須的,但這對於我們而言很方便。

return fetch(`http://www.subreddit.com/r/${subreddit}.json`)
  .then(
    response => response.json(),
    // 不要使用 catch,因為會捕獲
    // 在 dispatch 和渲染中出現的任何錯誤,
    // 導致 ‘Unexpected batch number‘ 錯誤。
    // https://github.com/facebook/react/issues/6895
     error => console.log(‘An error occurred.‘, error)
  )
  .then(json =>
    // 可以多次 dispatch!
    // 這裏,使用 API 請求結果來更新應用的 state。

    dispatch(receivePosts(subreddit, json))
  )

}
}

React開發中使用fetch進行異步請求