I have a problems with axios, in my code not execute the functions of my plugin, i am use vite.I can't bind my token in the headers.
interceptor.ts
import type { App } from "vue";
import axios from "axios";
export default {
install: (app: App): void => {
app.config.globalProperties.$http = axios;
const $http = app.config.globalProperties.$http;
const handleResponse = (response: unknown) => {
// ! this does not run
console.log('response :>> ', response);
return response;
};
const handleError = (err: unknown) => {
// ! this also does not
console.log('err :>> ', err);
return err;
}
$http.interceptors.response.use(handleResponse, handleError);
},
};
main.ts
import { createApp } from "vue";
import { createPinia } from "pinia";
import element_plus from "@/plugins/element-ui";
import interceptor from "@/plugins/interceptor";
import App from "./App.vue";
import router from "./router";
const app = createApp(App);
app.use(element_plus);
app.use(interceptor);
app.use(createPinia());
app.use(router);
app.mount("#app");
export default app;
package.json
"dependencies": {
"@bundled-es-modules/axios": "^0.27.2",
"boxicons": "^2.1.2",
"element-plus": "^2.2.0",
"pinia": "^2.0.13",
"vue": "^3.2.33",
"vue-router": "^4.0.14"
},
I have tried redaxios but without success. I can help me with a example?, thanks.
Solution
I found the solution, the key is to create an instance and make the export.
common-http.ts
import axios from "axios";
const baseURL = import.meta.env.VITE_BASE_API;
const apiClient = axios.create({
baseURL,
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": "*",
},
validateStatus: () => true,
});
export default apiClient;
then, I call the function on my interceptor.
import type { App } from "vue";
import type { AxiosResponse } from "axios";
import http from "@/utils/common-http";
export default {
install: (app: App): void => {
app.config.globalProperties.$http = http;
const $http = app.config.globalProperties.$http;
const handleResponse = (response: AxiosResponse) => {
// Here your code
console.log('response :>> ', response);
return response;
};
...