〔 前端筆記 〕Axios 與 Axios interceptors


共 1,753 字

前言

近期如火如荼得進行工作以外的 Side Project,主要負責 UI/UX、前端開發(更準確來說是前端 Vibe coding 😅),又再次接觸到 Axios 這個套件,因此想藉機再多認識它一點(近期的資安漏洞也讓我對它再次產生好奇😹)。至於 Side Project 待緣分到了可能也會再來分享也說不定~

Axios 是什麼?

先來看一下官方的簡介:

What is Axios? Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and node.js with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequest.

isomorphic 這個單字,可以拆解成:

  • iso :相同的
  • morph:形態、形狀
  • ic:形容詞

用生活化的例子來說,大致可以把 Axios 比擬成一個外送小哥哥,不管在 A 城市(瀏覽器)還是 B 城市(Node.js)都能接單送餐,而且消費者下單的方式完全一樣,不用因為城市不同而換一種叫法。

為什麼要用 Axios?Axios 的三大好處

1. 自動處理 JSON

如果不使用 Axios,使用 fetch 也可以打 api,但對於回傳回來的 JSON,fetch 還需多一步來解析:

const response = await fetch('/api/data');
const data = await response.json(); // 要多這一步

但使用 Axios 就可以一步到位:(直接拿到 JSON)

const { data } = await axios.get('/api/data'); 

2. 更細緻的錯誤處理

相對於 fetch 的錯誤訊息只鎖定在網路層面(例如網路斷線),Axios 可以針對非 2xx 的錯誤訊息,擁有更細緻的區別,讓接收到錯誤時不再受限於有限的線索,這點無庸置疑對於開發者與使用者都是一大幫助。

3. 擁有攔截器 interceptors

在前端送出 request 以前,可以透過 interceptors 來將 header 放入 request 中,一起送到後端以達到認證的目的;同樣得,可以先把後端回傳回來的錯誤訊息先攔截下來,進行細分後再顯示給使用者。另外,interceptors 可以讓所有 requests 都產生一樣的行為,像是全部的 requests 在送出前都需要在 header 帶上 token:

import axios from 'axios'

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
})

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('access_token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

只要在一個檔案(axios.js)定義好即可,無需每次發送都寫一遍,非常方便!

延伸: 如果都是打公開的 api(e.g. Ubike),就無需使用到 interceptors。所以攔截器 interceptors 也是根據專案需求來決定是否需要嘍~

References