Cheat Sheet速查表
跳转到主要内容

fetch() 速查表

本文根据 Devhints / fetch() 翻译。代码示例及版本范围沿用原文。

获取 (Fetch)

fetch('/data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  .catch(err => ...)

响应

fetch('/data.json')
.then(res => {
  res.text()       // response body (=> Promise)
  res.json()       // parse via JSON (=> Promise)
  res.status       //=> 200
  res.statusText   //=> 'OK'
  res.redirected   //=> false
  res.ok           //=> true
  res.url          //=> 'http://site.com/data.json'
  res.type         //=> 'basic'
                   //   ('cors' 'default' 'error'
                   //    'opaque' 'opaqueredirect')

  res.headers.get('Content-Type')
})

请求选项

fetch('/data.json', {
  method: 'post',
  body: new FormData(form), // post body
  body: JSON.stringify(...),

  headers: {
    'Accept': 'application/json'
  },

  credentials: 'same-origin', // send cookies
  credentials: 'include',     // send cookies, even in CORS

})

捕获错误

fetch('/data.json')
  .then(checkStatus)
function checkStatus (res) {
  if (res.status >= 200 && res.status < 300) {
    return res
  } else {
    let err = new Error(res.statusText)
    err.response = res
    throw err
  }
}

非 2xx 状态码的响应仍被视为成功的请求。请使用其他函数将其转换为错误。

与 node.js 配合使用

const fetch = require('isomorphic-fetch')

参见: isomorphic-fetch (npmjs.com)

参考资料