网络请求

@Fetch

Overview

fetch(url)
console.dir(fetch)

Syntax

fetch( url, {
  method: '',
  headers: {
    'Content-Type': 'application/json'
  },
  body: ''
} )
  .then( res => res.json() )
  .then( res => {
    console.log( 'success ', res )
  } )

Configuration

如果数据是 json 格式,可以省略 header 配置项;具体还要看服务器端的适配情况

Response

. 根据请求的数据类型,返回的结果分别有:
  1. res.json():得到 JSON 对象,同 JSON.parse(responseText) 一样;应用最广泛
  2. res.text():得到文字|字符串
  3. res.formData():得到 FormData 表单对象
  4. res.blob():得到 Blob对象,如图片等多媒体对象
[] 获取本地/远程 .json 数据 - 在开发者视图的控制台查看获取结果
[] text()
  1. 请求本地/远程文本文件 .txt
  2. fetch('./tmp.txt')
      .then(res => res.text())
      .then(res => console.log(res))
  3. 请求本地/远程 .html,实现模块化;不需要写完整的 html 结构,只写业务结构即可;见底部版权
  4. fetch('../../common/drill.html')
    .then(res => res.text())
    .then(res => {
      document.getElementById('require').innerHTML = res;
    })
[] formData() - 请求表单
[] blob() - 请求图片并渲染

异常处理

捕获的情况

. 网络层面失败,无法发起或完成请求 - A Fetch API promise will be rejected only in case of network failure.

无法捕获的情况

解决方案