Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { boot } from 'quasar/wrappers'
- import axios, { AxiosInstance } from 'axios'
- import { LocalStorage } from 'quasar'
- import { AUTH_TOKEN_LOCAL } from 'src/constants/auth'
- import utility from 'src/tools/utility'
- import { useRouter } from 'vue-router'
- import { Router } from 'src/router'
- import { useAuthStore } from 'src/store/auth'
- declare module '@vue/runtime-core' {
- interface ComponentCustomProperties {
- $axios: AxiosInstance
- }
- }
- // Be careful when using SSR for cross-request state pollution
- // due to creating a Singleton instance here;
- // If any client changes this (global) instance, it might be a
- // good idea to move this instance creation inside of the
- // "export default () => {}" function below (which runs individually
- // for each client)
- // const api = axios.create({ baseURL: 'https://api.example.com' });
- const api = axios.create({ baseURL: process.env.API_URL })
- api.interceptors.request.use(function (config) {
- const token = LocalStorage.getItem(AUTH_TOKEN_LOCAL)
- // console.log(utility.ReadSession(AUTH_TOKEN_LOCAL))
- if (token) {
- config.headers.common.Authorization =
- 'Bearer ' + utility.ReadSession(AUTH_TOKEN_LOCAL)
- }
- return config
- })
- api.interceptors.response.use(
- function (response) {
- api.defaults.headers.post['Content-Type'] =
- 'application/x-www-form-urlencoded'
- return response
- },
- function (error) {
- return Promise.reject(error)
- // return Promise.reject(error)
- }
- )
- export default boot(({ app, router }) => {
- const $router = useRouter()
- // for use inside Vue files (Options API) through this.$axios and this.$api
- app.config.globalProperties.$axios = axios
- // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
- // so you won't necessarily have to import axios in each vue file
- app.config.globalProperties.$api = api
- // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
- // so you can easily perform requests against your app's API
- api.interceptors.response.use(
- function (response) {
- return response
- },
- function (error) {
- const authStore = useAuthStore()
- const route = router.options.routes[0].name
- if (error.response.status === 401) {
- authStore.setIsLoggedin(false)
- localStorage.clear()
- router.push({ name: 'login' })
- // this.$router.go();
- // if (route !== "login") {
- // utility.notifySuccess("Login Expired");
- // }
- }
- return Promise.reject(error)
- }
- )
- })
- export { api }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement