I create one project with the vue-cli 3, so I run:
>vue create my-app;
>cd my-app
>vue add axios
the vue create in my my-app\src\plugins\ the file axios.js with this code:
"use strict";
import Vue from 'vue';
import axios from "axios";
// Full config: https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
let config = {
// baseURL: process.env.baseURL || process.env.apiUrl || ""
// timeout: 60 * 1000, // Timeout
// withCredentials: true, // Check cross-site Access-Control
};
const _axios = axios.create(config);
_axios.interceptors.request.use(
function(config) {
// Do something before request is sent
return config;
},
function(error) {
// Do something with request error
return Promise.reject(error);
}
);
// Add a response interceptor
_axios.interceptors.response.use(
function(response) {
// Do something with response data
return response;
},
function(error) {
// Do something with response error
return Promise.reject(error);
}
);
Plugin.install = function(Vue, options) {
Vue.axios = _axios;
window.axios = _axios;
Object.defineProperties(Vue.prototype, {
axios: {
get() {
return _axios;
}
},
$axios: {
get() {
return _axios;
}
},
});
};
Vue.use(Plugin)
export default Plugin;
but I need to in response interceptor access the vue-router, I already try to add the import Router from 'vue-router'; and use Roter.push() but when execute the say that push are not a method. I can't use This or Vue.$router too..
how can I fix this? tks
In order to use router inside axios interceptor or pretty much anywhere outside component's files, we have to import router instance of our application, that is created inside router entry file (by default router.js
).
Instance should be imported from the same path, as it is done in application's entry file (by default main.js
):
import router from './router'
This way all methods can be accessed, as described in documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With