iT邦幫忙

14

axios 基本使用 & Config

RocMark 2019-06-15 09:54:57154994 瀏覽

axios 介紹

  • 依賴 ES6 Promise,若不支援請使用 Polyfill
  • 支援 Promise API
  • 可取消請求 (Promise 無法)
  • 自動轉換 JSON
  • axios 實體建立

此筆記版本 v0.19.0

大綱

  • 安裝 / GET / POST 基礎用法
  • axios 一般寫法
  • axios API 寫法
  • axios 一次發送多個請求 (all)
  • axios async 範例
  • axios config 詳解

安裝

  • npm 安裝
  • 或掛 cdn
  $ npm install axios

GET / POST 基礎用法

  • 注意!!! axios 回傳並非直接是資料

console.log(res) 類似 request Object
內容包含: data / status / statusText / headers / config

  // 網址帶參數 或 傳入 params 物件
  axios.get('url/users?ID=123')
  axios.get('url/users', { params: { ID: 123 } })
    .then((res) => { console.table(res.data) })
    .catch((error) => { console.error(error) })
    .finally(() => { /* 不論失敗成功皆會執行 */ })

  // 資料由後方物件帶入
  axios.post('url/users', { name: 'Mark' })
    .then((res) => { console.table(res.data) })
    .catch((error) => { console.error(error) })

axios 一般寫法

  • axios(config 物件)
  • then result 回傳類似 reponseObject,其中 data 才是要的資料
  • 下面會介紹 如何統一使用 config 更易管理
  axios({
  method: 'get',
  baseURL: 'http://localhost:3000',
  url: '/users',
  'Content-Type': 'application/json',
})
  .then((result) => { console.log(result.data) })
  .catch((err) => { console.error(err) })

axios API 寫法

  • 使用以下寫法 不需要再將 url、method、data 寫在 config 裏面
  • config 用來撰寫 表頭、一些設定 (下有詳解)
  axios(config)
  axios.request(config) // 與上相同功能

  axios.get(url, config)
  axios.delete(url, config)
  // 功能與 GET 相同,但無 response body
  axios.head(url, config) 
  
  axios.post(url, data, config)
  axios.put(url, data, config)
  axios.patch(url, data, config)

  // 用來發送探測請求,確認該地址採用的協定、要求的表頭
  axios.options(url, config) // 預先檢查發送的請求是否安全

同時發送多個請求 all & spread

  • 類似 Promise All 用法
  • 注意 then 後接 axios.spread
  • 若直接用 如下 會得兩結果合併的陣列 (自行測試的結果)

then( res => console.log(res) )

  axios.all([funcA(), funcB()])
    .then(axios.spread((acct, perms) => {
      // axios 回傳的資料在 data 屬性
      console.table('FuncA 回傳結果', acct.data)
      // fetch 資料可以先在 function 內作 json()
      console.table('FuncB 回傳結果', perms)
    }))
    .catch((err) => { console.error(err) })

  function funcA() {
    return axios.get('http://localhost:3000/users/1')
  }

  function funcB() {
    return fetch('http://localhost:3000/users/2', {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
    }).then(res => res.json())
  }

搭配 async

  • 利用 try catch 作錯誤偵測
  • try 包裹所有 await 有錯誤則進入 catch
  getUsers()
  async function getUsers() {
    try {
      const post = await postUsers()
      const get = await axios.get('http://localhost:3000/users')
      const { data } = get // 資料在 data 屬性
      console.dir(get) // 回傳類似 RequestObject
      console.table(data)
    } catch (error) {
      throw new Error(error)
    }
  }

axios config 請求配置

  const config = {
    
    url: '/users',  // 只有此為必需
    method: 'post', // 大小寫皆可
    headers: { 'Content-Type': 'application/json' },
    
    // 添加在 url 前面,除非 url 為絕對路徑
    baseURL: 'http://localhost:3000'
    
    // 主要傳送的資料 (只用於 PUT、POST、PATCH )
    // 在沒有 transformRequest 情況下資料型別有限制 (下有補充)
    data: { name: 'test', title: 777 },

    // params 注意此不等同於 data
    // 此為 URL 上要代的參數   ~url?ID=123
    params: { ID: 123 }

    // 序列化參數 ???
    paramsSerializer: function(params) {
      return Qs.stringify(params, {arrayFormat: 'brackets'})
    },
    
    maxContentLength: 2000, // 限制傳送大小
        
    // 請求時間超過 1000毫秒(1秒),請求會被中止
    timeout: 1000,

    // 選項: 'arraybuffer', 'document', 'json', 'text', 'stream'
    // 瀏覽器才有 'blob' , 預設為 'json'
    responseType: 'json', // 伺服器回應的數據類型

    // 伺服器回應的編碼模式 預設 'utf8'
    responseEncoding: 'utf8',

    // 在上傳、下載途中可執行的事情 (progressBar、Loading)
    onUploadProgress(progressEvt) { /* 原生 ProgressEvent */  },
    onDownloadProgress(progressEvt) { /* 原生 ProgressEvent */ },

    // 允許自定義處理請求,可讓測試更容易 (有看沒懂..)
    // return promise 並提供有效的回應 (valid response)
    adapter (config) { /* 下方章節 補充詳細用法 */ },

  }

Config: 驗證 & Token

  • withCredentials (實用!!)
  • auth
  • validateStatus
  • xsrfCookieName / xsrfHeaderName
const config = {
    // 用來判斷是否為 跨域存取 (cross-site Access-Control requests)
    // 等同 Access-Control-Allow-Credentials 表頭
    // 用來解決 CORS
    withCredentials: false, // default

    // 必須提供 credentials (Cookie)
    // 等同 Authorization 表頭
    // 如果使用 token 應去 header 設置 Authorization 而非使用此
    auth: { username: 'Mark', password: 123 }
    
    // 用來判斷是否解析 Promise 的 狀態碼範圍
    validateStatus: function (status) {
      return status >= 200 && status < 300; // default
    },
    
    // xsrf token 的 Cookie名 / Header名
    xsrfCookieName: 'XSRF-TOKEN', // default
    xsrfHeaderName: 'X-XSRF-TOKEN', // default
    
    // 用來取消請求的 token (下詳)
    cancelToken: new CancelToken(function (cancel) {
    })
}

data 的資料型別

  • 在沒有 transformRequest 情況下資料型別有限制
  • 可在 transformRequest 中作資料轉換
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream

Config: 資料處理

  • 發送前 transformRequest
  • 使用前 transformResponse
  • 只用於 POST、PUT、PATCH
  const config = {
    // 資料發送至伺服器前,可作資料處理
    // 陣列中最後的函式必須返回字串、ArrayBuffer、Stream
    transformRequest: [function (data) {
      // 作資料轉換
      return data;
    }],

    // 在進入 then / catch 前可作資料處理
    transformResponse: [function (data) {
      // 作資料轉換
      return data;
    }],
  }

Config: Proxy 代理

  • 定義 代理伺服器的 Host、Port號
  • auth 代表 HTTP Basic auth 應用於連接代理,並提供 credentials
  • 會設置 Proxy-Authorization 表頭
  • 還有更詳細的參數設定,有需要在查 Github
  const config = {
    proxy: {
      host: '127.0.0.1',
      port: 9000,
      auth: {
        username: 'mikeymike',
        password: 'rapunz3l'
      }
    },
  }

node.js 相關 config

  • maxRedirects 定義 node.js 中要遵循的重定項最大數量
  • socketPath 定義 node.js 用的 UNIX Socket
  • httpAgent / httpsAgent
  const config = {
    // 設為 0,則不會重定向
    maxRedirects: 5, // default
    
    // Ex: '/var/run/docker.sock' 傳請求給 docker daemon
    // socketPath(優先權較高) & proxy 擇一使用
    socketPath: null, // default

    // 用於 node.js中執行 http/https的自定義代理
    // 默認不啟用,可配置成 keepAlive
    httpAgent: new http.Agent({ keepAlive: true }),
    httpsAgent: new https.Agent({ keepAlive: true }),
  }

參考資料

axios Github
axios 中文文檔(有些省略的)
axios小筆記
使用Axios你的API都怎麼管理?


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言