axios打API好管理
axios create
在前一篇《axios打API手不痠》介紹過 axios 的基本用法,這一篇來談談在業界實務上的做法。
前面有提到 axios 要帶上正確的方法與路徑才能接到資料,所以基本的寫法如下:
// axios.方法('路徑')
axios.get('https://randomuser.me/api/')
但是如果一個專案中要打 20 次相同的API,而且每一次都要寫一段很長的路徑,那就有點麻煩,程式碼也會冗長累贅不好閱讀。
這時如果想要寫的更簡潔,此時就可以使用 axios.create(axios instanece) 來建立簡短好閱讀的捷徑,同時也可以套用統一的 config ,除了不用每次打 API 都要重複寫一次之外,日後如果要修改,也可以在統一的地方修改管理,不用到處尋找四散在密密麻麻程式碼的 API 路徑來修改。
使用 axios.create來建立 axios 實例有以下優點:
- 在統一的地方管理路徑與 config。
- API 網址不再冗長且易於閱讀。
- 支援攔截器(axios.interceptors),可在 then/catch 前做額外處理
axios create 使用方法
axios.create([config])
官網上的範例:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
如果我們要打 randomuser API ,因為不用帶 headers 跟timeout,所以可以這樣創建實例:
// 創建實例
const randomUser = axios.create({
baseURL: "https://randomuser.me/api/"
// timeout: 1000,
// headers: { "X-Custom-Header": "foobar" },
});
那實際上打 API 的時候這樣寫,就不用寫一段冗長的 API 路徑了:
randomUser.get().then((res) => {
console.log("axios.create", res);
});
利用 axios.default 取得或改寫 config 的內容
console.log(randomUser.defaults.baseURL)
// 改寫baseURL
randomUser.defaults.baseURL = '改寫的路徑'
console.log(randomUser.defaults.headers.common)
// {
// "Accept": "application/json, text/plain, */*",
// "Content-Type": undefined
// }
console.log(randomUser.defaults.headers.common['Accept'])
// "application/json, text/plain, */*"
config的位置決定config的權重
https://axios-http.com/docs/config_defaults
axios 攔截器(Interceptors)
axios 攔截器可以在,在進入 .then 或 .catch 區塊之前攔截 api 發出的請求或取得的回應。
官方範例:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
以 randomUser API 為範例
// 創建實例
// baseURL: "https://randomuser.me/api/"
const randomUser = axios.create();
randomUser.defaults.baseURL = 'https://randomuser.me/api/';
randomUser.interceptors.request.use(function (config) {
console.log('config',config)
// 在 request 送出前攔截到此次的 config,讓你可以做最後的處理。
return config;
}, function (error) {
// 讓你在 request 發生錯誤時做一些額外的處理。
return Promise.reject(error);
});
randomUser.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
console.log('狀態碼',response.status)
return response;
}, function (error) {
// 錯誤處理
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
randomUser.get()
.then((res)=>{
console.log('a',res)
})
參考資料
- https://ithelp.ithome.com.tw/articles/10212121
- https://ithelp.ithome.com.tw/articles/10230336
- https://mini-ghost.dev/posts/axios-source-code-1/
- https://ithelp.ithome.com.tw/articles/10230336
- https://ithelp.ithome.com.tw/articles/10204698
- https://juejin.cn/post/7051209129985048584
- https://tw511.com/a/01/47171.html
- https://medium.com/i-am-mike/%E4%BD%BF%E7%94%A8axios%E6%99%82%E4%BD%A0%E7%9A%84api%E9%83%BD%E6%80%8E%E9%BA%BC%E7%AE%A1%E7%90%86-557d88365619
axios打API好管理
https://popeye-ux.github.io/2023/10/08/js-axios-create/