@Slav4ka

Как добавить перехватчик к нескольким axios запросам?

Я хочу добавить перехватчик ошибок в response. Запросы шлю при помощи axios. Сделать это хочу через interceptors. Вопрос такой: как мне не описывать interceptors для каждого fetch, а сделать это в одном месте?
import axios from 'axios';

export const fetchProfile = axios.create({
	baseURL: '/profile',
	headers: {
		'Content-Type': 'application/json',
		'Authorization': process.env.TOKEN,
	},
	withCredentials: true,
});

export const fetchCart = axios.create({
	baseURL: '/cart',
	headers: {
		'Content-Type': 'application/json',
		'Authorization': process.env.TOKEN,
	},
	withCredentials: true,
});

export const fetchCatalogs = axios.create({
	baseURL: '/catalogs',
	headers: {
		'Content-Type': 'application/json',
		'Authorization': process.env.TOKEN,
	},
	withCredentials: true,
});

export const fetchOrders = axios.create({
	baseURL: '/orders',
	headers: {
		'Content-Type': 'application/json',
		'Authorization': process.env.TOKEN,
	},
	withCredentials: true,
});

fetchOrders.interceptors.response.use(response => {
	console.log('yeeeeeeeeeeeeeeeeeeeeeeeee');
	console.log(response);

	return response;
}, error => {
	console.log('fuuuuuuuuuuuu');
	console.log(error);

	return Promise.reject(error);
});

export const fetchProducts = axios.create({
	baseURL: '/products',
	headers: {
		'Content-Type': 'application/json',
		'Authorization': process.env.TOKEN,
	},
	withCredentials: false,
});
  • Вопрос задан
  • 423 просмотра
Решения вопроса 1
bootd
@bootd
Гугли и ты откроешь врата знаний!
А накой чёрт создавать 100500 инстансов??
Раз хотите разделять endpoint'ы то создайте 1 инстанс, а от него создайте сервисы для разных модулей

// api.js
import axios from 'axios';

const API = axios.create({
  baseURL: 'https://mysite.com/api',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': process.env.TOKEN,
  },
  withCredentials: true,
});

API.interceptors.response.use(response => {
  console.log('yeeeeeeeeeeeeeeeeeeeeeeeee');
  console.log(response);

  return response;
}, error => {
  console.log('fuuuuuuuuuuuu');
  console.log(error);

  return Promise.reject(error);
});

export default API


// services/cart.js
import API from 'api'

export default {
  async getCart () {
    const { data } = await API.get('/cart')
  }
}


// services/catalog.js
import API from 'api'

export default {
  async getCatalog () {
    const { data } = await API.get('/catalog')
  }
}


С остальными по аналогии

Ну и использование:
// main.js
import { getCatalog } from 'services/catalog'
import { getCart } from 'services/cart'

async (() => {
  await Promise.all([
    getCatalog(),
    getCart()
  ])
})();
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы