I want to customize my get,post,put functions with axios. After doing the axios.create() operation, when I do the get operation, I want it to perform the then and catch operation there every time.
import axios from "axios";
export default (apiName = "") => {
let headers = {
"Content-Type": "application/json"
};
let token = JSON.parse(localStorage.getItem("token") || "{}");
if (token && token !== "") {
headers.Authorization = `Bearer ${token.AccessToken}`;
}
const instance = axios.create({
baseURL:
apiName === ""
? process.env.VUE_APP_API_URL
: process.env.VUE_APP_API_URL + apiName,
withCredentials: false,
headers: headers
});
return instance;
};
axios.post('/api/Export/CopyShippingPlan/', plan)
.then(handleResponse)
.catch((error) => {
console.log(error);
});
I want to define axios.post here after axios.create and have then and catch action wherever I call axios.post action. So I don't want to have to use then and catch where I use axios every time.
I think that you're looking for interceptors:
Example:
const ApiService = axios.create()
ApiService.interceptors.response.use(
config => {
//your code
return config
},
error => {
console.log(error)
return Promise.reject(error)
})
ApiService.interceptors.request.use(
config => {
//your code
return config
},
error => {
console.log(error)
return Promise.reject(error)
})
After setting them up you don't need to do anything special just call axios.get, axios.post, etc.