axios拦截器如何与axios.create()

时间:2020-06-20 15:08:13

标签: axios interceptor

我有以下代码,可以在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 :(得分:0)

经过一番摆弄之后,我已经解决了。

您必须首先使用axios.create()创建axios对象,然后将拦截器分配给该对象,之后您可以返回该对象。这是我使用的有效代码。

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

现在我知道该怎么做,我可以将授权代码移出create函数,并将其放入请求拦截器axiosInstance.interceptors.request.use