小编Rey*_*nor的帖子

在Next.js中,如何在axios拦截器中重定向页面?

我想在 axios 拦截器中重定向页面。

但是,当 服务器端渲染时,我无法访问 axios 拦截器中的服务器端上下文。所以我尝试使用 next/router。但它只适用于客户端。

我怎么可以这样呢?

下面是axios拦截器中执行的函数。

// customAxios.ts
const customAxios = axios.create();

customAxios.interceptors.response.use((response) => response, responseErrorHandler);
Run Code Online (Sandbox Code Playgroud)
// responseErrorHandler.ts
const responseErrorHandler = (error: AxiosError): Promise<AxiosError> => {
  if (error.response) {
    if (error.message === TIMEOUT_MESSAGE) {
      if (typeof window === 'undefined') {
         // Redirect to /503 page in server side rendering
      } else {
        window.location.href = '/503';
      }
    }
  }

  return Promise.reject(error);
}
Run Code Online (Sandbox Code Playgroud)

typescript axios next.js

4
推荐指数
1
解决办法
5559
查看次数

标签 统计

axios ×1

next.js ×1

typescript ×1