purityselect/resources/js/plugins/axios.js
2024-10-25 01:05:27 +05:00

59 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import router from '@/router'
import axios from 'axios'
const axiosIns = axios.create({
// You can add your headers here
// ================================
// baseURL: 'https://some-domain.com/api/',
// timeout: 1000,
// headers: {'X-Custom-Header': 'foobar'}
})
// Add request interceptor to send the authorization header on each subsequent request after login
axiosIns.interceptors.request.use(config => {
// Retrieve token from localStorage
const token = localStorage.getItem('access_token')
// If token is found
if (token) {
// Get request headers and if headers is undefined assign blank object
config.headers = config.headers || {}
// Set authorization header
// JSON.parse will convert token to string
config.headers.Authorization = token ? `Bearer ${token}` : ''
}
// Return modified config
return config
})
// Add response interceptor to handle 401 response
axiosIns.interceptors.response.use(response => {
return response
}, error => {
// Handle error
if (error.response.status === 401) {
// Logout user and redirect to login page
// Remove "userData" from localStorage
localStorage.removeItem('userData')
// Remove "accessToken" from localStorage
localStorage.removeItem('access_token')
localStorage.removeItem('userAbilities')
// If 401 response returned from api
if (requestedUrl.pathname === '/provider/login') {
router.push('/provider/login');
} else if (requestedUrl.pathname === '/login') {
router.push('/login');
}
}
else {
return Promise.reject(error)
}
})
export default axiosIns