章節連結
當 Dev 的 Proxy 需要指向非網域根目錄的路徑,但又想要保有指向根目錄的彈性時,除了用 Axios 的攔截器來修改 baseURL 外,也可用新增多個 Axios 來達成。這邊筆記下實作方法。
內容
1. 新增一支 .js (.ts) 來統一管理你的 axios,最後將設定好的 Instances 給匯出 export
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import axios, { AxiosInstance } from 'axios' import { BuildENV, APIResponseString } from '@/types' // Declare axios instance const axiosRootInstance = axios.create({ baseURL: import.meta.env.VITE_BUILD_ENV === BuildENV.development ? '/api/' : '/', }) const axiosAnotherInstance = axios.create({ baseURL: import.meta.env.VITE_BUILD_ENV === BuildENV.development ? '/api/another' : '/another', }) // Add interceptors const addInterceptors = (instance: AxiosInstance) => { instance.interceptors.request.use( function (config) { // Do something before request is sent return config }, function (error) { // Do something with request error return Promise.reject(error) }, ) instance.interceptors.response.use( function (response) { const errorStrArray = Object.values(APIResponseString) const errorNeedReLogin = [APIResponseString.logout] if (errorStrArray.includes(response.data)) { console.log('error') if (errorNeedReLogin.includes(response.data)) { // Re-login redirect window.location.href = import.meta.env.VITE_BUILD_ENV === BuildENV.development ? './' : '../signin.html' } } 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) }, ) } addInterceptors(axiosRootInstance) addInterceptors(axiosAnotherInstance) export { axiosRootInstance, axiosAnotherInstance } |
2. 接著 vite 的 server 設定檔也要進行修改。越嚴格的判別條件要在越上層,否則進行攔截時會出錯
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{ server: { proxy: { '/api/another': { target: 'https://demo.com/another', changeOrigin: true, rewrite: (path) => path.replace(/^\/api\/another/, ''), }, '/api': { target: 'https://demo.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), }, }, } } |
按讚加入粉絲團