關於h5中的fetch方法解讀

1. 前言

既然是h5的新方法,確定就有一些比較older的瀏覽器不支持了,對於那些不支持此方法的
瀏覽器就須要額外的添加一個polyfill:

[連接]: https://github.com/fis-components/whatwg-fetch

2. 用法

ferch(抓取) :html

HTML:
fetch('/users.html') //這裏返回的是一個Promise對象,不支持的瀏覽器須要相應的ployfill或經過babel等轉碼器轉碼後在執行
    .then(function(response) {
    return response.text()})
    .then(function(body) {
    document.body.innerHTML = body
})
JSON :
fetch('/users.json')
    .then(function(response) {
    return response.json()})
    .then(function(json) {
    console.log('parsed json', json)})
    .catch(function(ex) {
    console.log('parsing failed', ex)
})
Response metadata :
fetch('/users.json').then(function(response) {
  console.log(response.headers.get('Content-Type'))
  console.log(response.headers.get('Date'))
  console.log(response.status)
  console.log(response.statusText)
})
Post form:
var form = document.querySelector('form')

fetch('/users', {
  method: 'POST',
  body: new FormData(form)
})
Post JSON:
fetch('/users', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({  //這裏是post請求的請求體
    name: 'Hubot',
    login: 'hubot',
  })
})
File upload:
var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0]) //這裏獲取選擇的文件內容
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})

3. 注意事項

(1)和ajax的不一樣點:
1. fatch方法抓取數據時不會拋出錯誤即便是404或500錯誤,除非是網絡錯誤或者請求
過程當中被打斷.但固然有解決方法啦,下面是demonstration:
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) { //判斷響應的狀態碼是否正常
    return response //正常返回原響應對象
  } else {
    var error = new Error(response.statusText) //不正常則拋出一個響應錯誤狀態信息
    error.response = response
    throw error
  }
}

function parseJSON(response) {
  return response.json()
}

fetch('/users')
  .then(checkStatus)
  .then(parseJSON)
  .then(function(data) {
    console.log('request succeeded with JSON response', data)
  }).catch(function(error) {
    console.log('request failed', error)
  })
2.一個很關鍵的問題,fetch方法不會發送cookie,這對於須要保持客戶端和服務器端
常鏈接就很致命了,由於服務器端須要經過cookie來識別某一個session來達到保持會
話狀態.要想發送cookie須要修改一下信息:
fetch('/users', {
  credentials: 'same-origin'  //同域下發送cookie
})
fetch('https://segmentfault.com', {
  credentials: 'include'     //跨域下發送cookie
})

下圖是跨域訪問segment的結果
clipboard.pnggit

Additional

若是不出意外的話,請求的url和響應的url是相同的,可是若是像redirect這種操做的
話response.url可能就會不同.在XHR時,redirect後的response.url可能就不太準
確了,須要設置下:response.headers['X-Request-URL'] = request.url
適用於( Firefox < 32, Chrome < 37, Safari, or IE.)
相關文章
相關標籤/搜索