保誠-保戶業務員媒合平台
劉鈞霖
2021-12-13 03e4c7d29fe2886571229df7aeab0f1dde54be15
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
55
56
57
58
59
60
61
62
63
64
65
66
67
import { AxiosRequestConfig, AxiosError, AxiosResponse} from 'axios';
import ErrorMessageBox from '../errorService';
import axios from 'axios';
import _ from 'lodash';
 
const notRequireInterceptorErrorUrl = [
  '/otp/verify',
  '/eService/authenticate',
  '/login/validate/get_img_code',
  '/login/validate/verify_img_code',
];
 
export const service = axios.create({
  baseURL: process.env.BASE_URL,
  withCredentials: true
});
 
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    loadingStart();
    addHttpHeader(config);
    return config;
  }
);
 
service.interceptors.response.use(
  (response: AxiosResponse) => {
    loadingFinish();
    return response;
  },
  (error: AxiosError) => {
    loadingFinish();
    showErrorMessageBox(error)
    return Promise.reject(error);
  }
);
 
function addHttpHeader(config: AxiosRequestConfig): void {
  config.headers = {
    Authorization: 'Bearer ' + localStorage.getItem('id_token')
  }
}
 
function loadingStart(): void {
  window.$nuxt.$loading.start();
};
 
function loadingFinish(): void {
  window.$nuxt.$loading.finish();
};
 
function showErrorMessageBox(error: any): void {
  // console.log('error', error, error.response);
  if (!_.includes(notRequireInterceptorErrorUrl, error.config.url)) {
    switch (error.response.status) {
      case 401:
        Promise.all([ErrorMessageBox('登入逾時'), window.$nuxt.$store.dispatch('localStorage/actionStorageClear')]).then(() => {
          _.isEqual(window.$nuxt.$route.name, 'index') ? location.reload() : window.$nuxt.$router.push('/');
        });
        break;
 
      default:
        ErrorMessageBox('', error);
        break;
    }
  }
};