Last active
September 14, 2021 18:53
-
-
Save xelinel32/900a30eed99e69426d35bb62ce82da9d to your computer and use it in GitHub Desktop.
Axios config from Vue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios' | |
export default () => { | |
const axiosInstance = axios.create({ | |
baseURL: `${process.env.VUE_APP_URL}/api/v1`, | |
}) | |
const token = localStorage.getItem('token') | |
if (token) { | |
axiosInstance.defaults.headers.common.Authorization = `Bearer ${token}` | |
} | |
axiosInstance.interceptors.response.use( | |
(response) => response, | |
(error) => { | |
if (error.response.status === 401) { | |
localStorage.removeItem('token') | |
localStorage.removeItem('user') | |
location.reload() | |
} | |
return Promise.reject(error) | |
}, | |
) | |
return axiosInstance | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from "axios"; | |
import Vue from "vue"; | |
const http = axios.create({ | |
url: "/", | |
baseURL: "/api/", | |
timeout: 2000, | |
responseType: "json", | |
responseEncoding: "utf8", | |
headers: { "content-type": "application/json" } | |
}); | |
const token = localStorage.getItem("user-token"); | |
if (token) { | |
http.defaults.headers.common["Authorization"] = token; | |
} | |
Vue.prototype.$http = http; | |
// рефреш токена если время его действия истекло | |
created: function () { | |
this.$http.interceptors.response.use((response) => { | |
return response | |
}, (error) => { | |
if (error.response.status === 401) { | |
if (this.$store.getters.authorized) { | |
this.$store.dispatch('refreshtoken') | |
} else { | |
return Promise.reject(error) | |
} | |
} else { | |
return Promise.reject(error) | |
} | |
}) | |
} | |
export default http; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Base implementation
axios
in a test project