ax ios перехватчики, как их использовать с ax ios .create () - PullRequest
0 голосов
/ 20 июня 2020

У меня есть следующий код, который я импортирую и использую в приложении VueJS.

Я хочу иметь возможность централизованно возвращать ошибки, возвращаемые API, и кажется, что перехватчики сделают эту работу за меня, но Я не понимаю, где я их установил

import axios from 'axios'
import store from './store/index'

export default () => {
  try{
    var token = store.state.user.token.token
  }catch(err){
    var token = ""
  }

  return axios.create({
    baseURL: "http://localhost:3333/api/v1",
    headers: {
      "Authorization": `Bearer ${token}`
    }
  })
  
}

Я пробовал это, но это не работает.

import axios from 'axios'
import store from './store/index'

axios.interceptors.request.use((config) => {
  console.info("debug ", config);
  return config;
}, (error) => {
  console.error("debug ", error);
  return Promise.reject(error);
});

export default () => {
  try{
    var token = store.state.user.token.token
  }catch(err){
    var token = ""
  }

  return axios.create({
    baseURL: "http://localhost:3333/api/v1",
    headers: {
      "Authorization": `Bearer ${token}`
    }
  })
  
}

1 Ответ

0 голосов
/ 20 июня 2020

После некоторой игры я решил это.

Вы должны сначала создать объект ax ios с axios.create(), затем назначить свои перехватчики на объект, после чего вы можете вернуть объект. Вот код, который я использовал, который работал.

var axiosInstance = axios.create({
    baseURL: "http://localhost:3333/api/v1",
    headers: {
      "Authorization": `Bearer ${token}`
    },
   
  })

  //This allows you to intercept the request before it is sent and alter headers or anyting else that is passed to the axios config.
  axiosInstance.interceptors.request.use((config)=>{
    return config
  }, (error) => {
    console.log("Interceptor Request Error" + error)
  })

  //This allows you to intercept the response and check the status and error messages and if ncessary reject the promise.
  axiosInstance.interceptors.response.use((response) => {
    console.log(response.data)
    return response
  }, (error) => {
    console.log("Interceptor Response Error" + error)
  })
  return axiosInstance

Теперь я знаю, как это сделать, я мог бы переместить свой код авторизации из функции создания и поместить его в перехватчик запросов axiosInstance.interceptors.request.use

...