Skip to content

Instantly share code, notes, and snippets.

@xelinel32
Last active September 14, 2021 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xelinel32/900a30eed99e69426d35bb62ce82da9d to your computer and use it in GitHub Desktop.
Save xelinel32/900a30eed99e69426d35bb62ce82da9d to your computer and use it in GitHub Desktop.
Axios config from Vue
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
}
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;
@xelinel32
Copy link
Author

Base implementation axios in a test project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment