| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import axios from 'axios';
- import type {
- InternalAxiosRequestConfig,
- AxiosResponse,
- AxiosRequestHeaders,
- } from 'axios';
- import { Message, Modal } from '@arco-design/web-vue';
- import { useUserStore } from '@/store';
- import { getToken } from '@/utils/auth';
- const instance = axios.create({
- baseURL: import.meta.env.VITE_API_BASE_URL,
- });
- instance.interceptors.request.use(
- (config: InternalAxiosRequestConfig) => {
- // let each request carry token
- // this example using the JWT token
- // Authorization is a custom headers key
- // please modify it according to the actual situation
- const token = getToken();
- if (token) {
- if (!config.headers) {
- config.headers = {} as AxiosRequestHeaders;
- }
- config.headers.Authorization = `Bearer ${token}`;
- }
- return config;
- },
- error => {
- // do something
- return Promise.reject(error);
- }
- );
- // 响应拦截器修复版本
- instance.interceptors.response.use(
- (response: AxiosResponse) => {
- const res = response.data;
- console.log('res', res);
- if (response.status === 401) {
- Modal.error({
- title: 'Confirm logout',
- content:
- 'You have been logged out, you can cancel to stay on this page, or log in again',
- okText: 'Re-Login',
- async onOk() {
- const userStore = useUserStore();
- await userStore.logout();
- window.location.reload();
- },
- });
- }
- return response;
- },
- error => {
- Message.error({
- content: error.message || 'Request Error',
- duration: 5 * 1000,
- });
- return Promise.reject(error);
- }
- );
- export default instance;
|