Initial commit
This commit is contained in:
39
plugins/axios.ts
Normal file
39
plugins/axios.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'
|
||||
import { mapState } from 'pinia'
|
||||
import type { Logger } from 'pino'
|
||||
import { useUserStore } from '~/stores/user'
|
||||
export default defineNuxtPlugin(() => {
|
||||
if (useRuntimeConfig().public.apiUrl === '') {
|
||||
throw new Error('Please ensure that the apiUrl is set in .env File.')
|
||||
}
|
||||
const defaultUrl = useRuntimeConfig().public.apiUrl
|
||||
|
||||
|
||||
// Access Pinia state
|
||||
// @ts-ignore
|
||||
const api: AxiosInstance = axios.create({
|
||||
// @ts-ignore
|
||||
baseURL: defaultUrl,
|
||||
headers: {
|
||||
common: {}
|
||||
},
|
||||
withCredentials: true
|
||||
})
|
||||
// @ts-ignore
|
||||
api.interceptors.request.use((config: AxiosRequestConfig) => {
|
||||
|
||||
|
||||
const logger = useNuxtApp().$logger as any
|
||||
logger.info("BACKEND URL "+ defaultUrl)
|
||||
config.baseURL = defaultUrl
|
||||
const token = mapState(useUserStore, ['token']).token()
|
||||
// @ts-ignore
|
||||
config.headers.Authorization = 'Bearer ' + token
|
||||
return config
|
||||
})
|
||||
return {
|
||||
provide: {
|
||||
axios: api
|
||||
}
|
||||
}
|
||||
})
|
Reference in New Issue
Block a user