Для вызовов ax ios вы можете создать функцию или класс и импортировать их каждый раз
Что-то вроде services/axios
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: process.env.VUE_APP_BASE_URL,
headers: {
'Access-Control-Allow-Origin': '*',
accept: 'Accept: application/json',
},
});
export default axiosInstance;
А потом в utils/requests
import axiosInstance from '@/services/axios';
const apiRequest = async (axiosConfig) => {
try {
const response = await axiosInstance(axiosConfig);
return {
success: true,
data: response.data.data || response.data;
}
} catch (error) {
if (error.response) {
error = error.response
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
error = error.request
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
error = error.message
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
return {
success: false,
error
}
}
};
export const getRequest = async (url) =>
await apiRequest({
method: 'GET',
url,
});
export const postRequest = async(url, requestBody) =>
await apiRequest({
method: 'POST',
url,
data: requestBody
});
Затем вы импортируете методы getRequest и postRequest в компоненты
component. vue
import { getRequest, postRequest } from '@/utils/requests';
const response = await postRequest('/url', requestBody);
if (response.success) {
// do stuff on success
} else {
// error message
}