fetch基本認知

  1. 發送請求方法:

    1. 通過Ajax向服務器請求數據,使用XMLHttpRequest對象實現

      1
      2
      3
      4
      5
      6
      const xhr = new XMLHttpRequest()
      xhr.open('GET', 'url')
      xhr.send()
      xhr.addEventListener('LOAD', () => {
      console.log(JSON.parse(xhr.response))
      })
    2. 通過axios實現,代碼精簡但底層仍然基於XMLHttpRequest對象實現,本質只是進行Promise封裝

  1. fetch簡介:
    • 被稱為下一代的Ajax技術,內部採用Promise方法處理數據 (可以直接使用.then)
    • API語法簡潔
    • 採用模塊化設計,API分散於多個對象中 (Responnse對象、Request對象、Header對象)
    • 通過數據流 (Stream對象)處理數據,可以分塊讀取,有利於提高網站性能

GET請求

  1. 簡介:
    • 如果fetch()只接收一個url字符串參數,表示默認向網址發送GET請求,會返回一個Promise對象
  1. 基本使用
    • 具體編碼
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      fetch('http://127.0.0.1:8080/test_fetch_get').then(res => {
      // 直接得到的 res 是一個 Response 對象
      console.log(res)

      // res.json() 是一個異步操作,表示取出所有內容,並轉換成 JSON 對象
      return res.json()

      }).then(json => {
      // 獲取處理過的數據
      console.log(json)

      }).catch(err => {
      // 捕獲錯誤信息
      console.error(err)
      })
  1. 把代碼封裝成async異步函數
    • 具體編碼:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      async function getData(){
      // 通過 try...catch 處理 async 和 await 成功和失敗情
      try {
      // 先獲取 Response 對象
      let res = await fetch('http://127.0.0.1:8080/test_fetch_get')
      console.log(res)

      // 通過 res.json() 取出 Response 對象中的結果
      let json = await res.json()
      console.log(json)

      } catch (err) {
      console.error(err)
      }
      }
      getData()

Respons對象

  1. 常見屬性:
    | 屬性 | 含義 |
    | :—-: | :—-: |
    | res.ok | 返回boolean,表示請求是否成功 |
    | res.status | 返回數字,表示HTTP響應的狀態碼(例如:200表示請求成功) |
    | res.statusText | 返回狀態的文本信息 |
    | res.url | 返回請求的url地址值 |
  1. 常見方法:
    | 方法 | 含義 |
    | :—-: | :—-: |
    | res.json() | 得到 JSON 對象 |
    | res.text() | 得到文本字符串 |
    | res.blob() | 得到二進制 Blob 對象 |
    | res.formData() | 得到 FormData 表單對象 |
    | res.arrayBuffer() | 得到二進制 ArrayBuffer 對象 |

POST請求

  1. 簡介:
    • fetch()可以傳遞第二個參數指定請求的方式
    • 配置參數:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      fetch('url', {
      // 請求方法
      method: '',
      // 設置請求頭
      headers: {
      // 數據格式
      'Content-Type': ''
      },
      // 配置請求體數據
      body: ''
      })
  1. JSON格式:
    • 設置請求頭:'Content-Type': 'application/json'
    • 具體編碼:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      async function add(){
      let obj = {name:'Donald', age:18, gender: 'M'}

      let res = await fetch('http://127.0.0.1:8080/test_fetch_post', {
      method: 'POST',
      headers: {
      'Content-Type': 'application/json'
      },
      body: JSON.stringify(obj)
      })

      console.log(res.json())
      }
      add()
  1. urlencoded格式:
    • 設置請求頭:'Content-Type': 'application/x-www-form-urlencoded'
    • 具體編碼:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      async function add(){
      let res = await fetch('http://127.0.0.1:8080/test_fetch_post', {
      method: 'POST',
      headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: 'name=Donald&age=18&gender=M'
      })
      console.log(res.json())
      }
      add()

fetch函數封裝

  1. 簡介:
    • fetch相比XMLHttpRequest已經方便很多,但參數仍須自己處理
      • GET, DELETE的請求參數需要寫在地址欄裡
      • PUT, PATCH, POST的請求參數需要轉JSON設置請求頭
  1. 二次封裝效果:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    // 發送GET、DELETE請求
    http({
    method:'XXX',
    url:'xxx',
    params: {...}
    })

    // 發送POST、PUT、PATCH請求
    http({
    method:'XXX',
    url:'xxx',
    data: {...}
    })
  1. 具體編碼:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    async function http({method, url, params, data}){
    // params 需要轉換成 key=value&key=value 的形式
    if(params){
    // 固定寫法: new URLSearchParams(params).toString()
    let str = new URLSearchParams(params).toString()
    // 拼接到 url
    url += '?' + str
    }

    // 最終結果
    let res
    // data 需要寫完整的代碼
    if(data){
    res = await fetch(url, {
    method,
    headers: {
    'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
    })
    }else{
    res = await fetch(url)
    }
    return res.json()
    }