Previously, I used to import axios in each Vue component separately when making HTTP requests. An example of this can be seen below:
<script lang="ts">
import axios from 'axios';
@Component
export default class ExamplePage extends Vue {
created(): void {
axios.post(some_path);
}
}
However, I have now realized the importance of setting up a global interceptor for all axios requests. This would help in handling 401 unauthorized
responses from the backend server (Rails) and logging out the user accordingly.
According to my research on Stack Overflow and similar articles, I attempted the following approach.
// application.js
import '../assets/sass/base.sass';
import App from '../app';
import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from 'axios';
import router from '../routes';
Vue.use(VueRouter);
document.addEventListener('DOMContentLoaded', () => {
new Vue({
el: '#application',
router,
render: (h) => h(App),
});
});
axios.interceptors.response.use(
response => response,
error => {
const status = error.response;
if(status === 401) {
// do stuff
}
}
);
Vue.prototype.$http = axios
Even after trying to call this.$http.put(...)
in another file, I encountered an issue where the property $http
was not recognized. It seems that the context of the component might be causing this problem, but I'm unsure how to resolve it. Any suggestions?
[UPDATE] Following the advice received, I attempted initializing an axios instance in a separate file. However, I am still facing issues as the 401 responses are not triggering the interceptor as expected.
Do I need to include additional configurations? Any insights would be appreciated.
// axios-instance.ts
import axios, { AxiosInstance } from 'axios';
const axiosInstance: AxiosInstance = axios.create();
axiosInstance.interceptors.response.use(
response => response.data,
async function(error) {
console.log("THIS IS THE 401 INTERCEPTOR")
const status = error.response;
if(status === 401) {
// Log out user
}
}
);
export default axiosInstance;
// Some component
<script lang="ts">
import axiosInstance from 'axios-instance';
@Component
export default class ExamplePage extends Vue {
created(): void {
axiosInstance.post(some_path);
}
}