PrestonDocks
PrestonDocks

Reputation: 5408

axios interceptors how to use them with axios.create()

I have the following code which I import and use in a VueJS application.

I want to be able to errors returned by the API centrally and it seems that interceptors would do the job for me but I don't understand where I set them up

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}`
    }
  })
  
}

I have tried this, but it does not work.

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}`
    }
  })
  
}

Upvotes: 2

Views: 5850

Answers (1)

PrestonDocks
PrestonDocks

Reputation: 5408

After some fiddling, I have worked it out.

You have to first create an axios object with axios.create(), then assign your intercepters to the object after which you can return the object. Here is the code I used that worked.

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

Now I know how to do this, I could move my Authorization code out of the create function and put it in the request interceptor axiosInstance.interceptors.request.use

Upvotes: 1

Related Questions