显示来自axios响应拦截器的模态。反应

问题描述 投票:1回答:1

我有一个小项目,我使用的是没有Redux或Router的React。我也为每个请求使用axios。

我需要做的是,如果任何响应都有401错误代码,我需要显示带有适当错误消息的某种模式。

我创建了一个axios实例,并在此处设置了响应拦截器:

const axiosInstance = axios.create({
  baseURL: URL_PREFIX,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
})

axiosInstance.interceptors.response.use(
  response => response,
  error => {
    if(error.response.status === 401) {
      // I want to show modal from here, 
      // but this is outside of my component tree
      // and I can not access my modal state to set it open.
    }
    return error
  }
)

然后我将创建的axios实例用于每个API调用。

我还尝试从根组件useEffect()方法设置响应拦截器。但这不起作用

没有使用Redux或Router的方法有什么好的方法吗?

reactjs axios interceptor
1个回答
0
投票

您可以使用axios.catch()方法:

axios.get('url')
  .then(response => // response.data )

  .catch((error) => {
    if (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.status);
    } else if (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 {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

更新:

创建实例模块

// axiosInstance.js
import axios from "axios"

const axiosInstance = axios.create({
  baseURL: "url"
})

// You can do the same with `request interceptor`
axiosInstance.interceptors.response.use(
  response => {
    // intercept response...
    return response
  },
  error => {
    // intercept errors
    return error
  }
)
// You can create/export more then one
export { axiosInstance }

然后import在您的组件中:

import { axiosInstance } from "./axiosInstance"

const SomeComponent = () => {
  // You may want to use state to store the returned values ...

  useEffect(() => {
    // Call the instance
    axiosInstance.get().then(res => {
      if (res.status === 200) {
        // Everything is OK

        // Else, check if the error object is exist
      } else if (res.response) {
        // Error object: `res.response`
        // For error codes: `res.response.status`
        if(res.response.status === 401) {
          // Do your stuff
        }
      }
    })
  }, [])

  return ( ... )
}

Edit react useContext hook

© www.soinside.com 2019 - 2024. All rights reserved.