1// Add a request interceptor
2axios.interceptors.request.use(function (config) {
3 // Do something before request is sent
4 return config;
5 }, function (error) {
6 // Do something with request error
7 return Promise.reject(error);
8 });
9
10// Add a response interceptor
11axios.interceptors.response.use(function (response) {
12 // Any status code that lie within the range of 2xx cause this function to trigger
13 // Do something with response data
14 return response;
15 }, function (error) {
16 // Any status codes that falls outside the range of 2xx cause this function to trigger
17 // Do something with response error
18 return Promise.reject(error);
19 });
1// Add a response interceptor
2HTTP.interceptors.response.use(function (response) {
3 return response
4}, function(error) {
5 if (error.response.status === 401) {
6 store.dispatch('logout')
7 router.push('/login')
8 }
9 return Promise.reject(error.response.data)
10})
11
1window.axios = require('axios');
2
3axios.interceptors.request.use(
4 config => {
5 /* ---- 'Accept': 'application/json',
6 'Authorization': this.token, ---- */
7 config.headers['Accept']= 'application/json'
8
9 let token = document.cookie.split(';').find(indice => {
10 return indice.includes('token=')
11 })
12
13 token = token.split('=')[1]
14 token = 'Bearer ' + token
15
16 config.headers.Authorization = token
17 console.log('Intercepting the request before sending it', config)
18 return config // nxt jwt.php
19 },
20 error => {
21 console.log("Request error: ", error)
22 return Promise.reject(error)
23 })
24
25axios.interceptors.response.use(
26 response => {
27 console.log('Intercepting the response before sending it', response)
28 return response
29 },
30 error => {
31 console.log("Answer Error: ", error.response)
32
33 if( error.response.status == 401 && error.response.data.message == 'Token has expired')
34 {
35 console.log('Make a new request for the refresh route!')
36
37 axios.post('http://localhost:8000/api/refresh')
38 .then(response => {
39 console.log('Refresh success! ')
40 console.log(response)
41 /*
42 In the first refresh, will be sucess but if I don't save the
43 token in cookies, in the second refresh I will have the 500
44 error : 'The token has been blacklisted'
45 */
46 document.cookie = 'token=' + response.data.token
47 console.log('Updated token : ' , response.data)
48 window.location.reload()
49 })
50 }
51 return Promise.reject(error)
52 })
53