前言
請求攔截器,是每一次發送請求時的中介層:
1 2 3 4 5
| axios.interceptors.request.use((config) => { return config; }, (e) => { return Promise.reject(e); });
|
響應攔截器,是每一次接收響應時的中介層:
1 2 3 4 5
| axios.interceptors.response.use((res) => { return res; }, (e) => { return Promise.reject(e); });
|
範例
以下在每一次發送請求時都帶上 token 令牌,並且在每一次接收響應時都檢查 HTTP 狀態:
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
| import axios from 'axios'; import store from '@/store'; import router from '@/router';
const client = axios.create({ baseURL: process.env.VUE_APP_API_URL, });
client.interceptors.request.use((config) => { const { token } = store.state; const decoded = Buffer.from(token || '', 'base64').toString(); if (decoded) { config.headers.Authorization = `Bearer ${decoded}`; } return config; });
client.interceptors.response.use( (res) => res, async (e) => { if (e?.response?.status === 401) { await router.push({ name: 'logout' }); } return Promise.reject(e); }, );
export default client;
|