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

Dit*_*ito 5 interceptor reactjs axios

我有一个小项目,我在没有 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
  }
)
Run Code Online (Sandbox Code Playgroud)

然后我为每个 API 调用使用我创建的 axios 实例。

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

有没有什么好的方法可以在不使用 Redux 或 Router 的情况下实现这一点?

awr*_*an5 3

您可以使用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);
  });
Run Code Online (Sandbox Code Playgroud)

更新:

创建实例模块

// 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 Promise.reject(error)
  }
)
// You can create/export more then one
export { axiosInstance }
Run Code Online (Sandbox Code Playgroud)

然后将其导入到您的组件中:

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 ( ... )
}
Run Code Online (Sandbox Code Playgroud)

编辑react useContext钩子

  • 感谢你的回答。但这意味着我必须分别捕获每个请求的错误。我需要利用拦截器的优势,它会跨越使用 axios 发送的每个请求并处理那里的错误和成功。 (4认同)