小编Dit*_*ito的帖子

显示来自 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() 方法设置响应拦截器。但它不起作用

有没有什么好的方法可以在不使用 …

interceptor reactjs axios

5
推荐指数
1
解决办法
3450
查看次数

标签 统计

axios ×1

interceptor ×1

reactjs ×1