【问题标题】:In Next.js, How to Redirect page in axios interceptor?在 Next.js 中,如何在 axios 拦截器中重定向页面?
【发布时间】:2022-01-09 11:20:33
【问题描述】:

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

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

我怎么能这样?

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

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

customAxios.interceptors.response.use((response) => response, responseErrorHandler);
// 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);
}

【问题讨论】:

    标签: typescript axios next.js


    【解决方案1】:

    如果没有看到 getServerSidePropsgetStaticProps 的实际实现,很难给出答案,但这可能会有所帮助。 您的拦截器可能会抛出您可以在这些方法中识别的自定义错误,然后使用Next.js redirects

    // responseErrorHandler.ts
    const responseErrorHandler = (error: AxiosError): Promise<AxiosError> => {
      if (error.response) {
        if (error.message === TIMEOUT_MESSAGE) {
          if (typeof window === 'undefined') {
             throw new CustomError(); //Throw custom error here
          } else {
            window.location.href = '/503';
          }
        }
      }
    
      return Promise.reject(error);
    }
    

    然后,在取数据的方法中(需要适配Typesctipt):

    export async function getServerSideProps(context) {
    
      try {
        await customAxios.get(...)
      } catch(e) {
        if (e instanceof CustomError){
          return {
            redirect: {
              destination: '/503'
            }
          };
        } else { 
            //...
        }
      }
    
      //...
    }
    

    【讨论】:

    • 谢谢。我会看看。谢谢:)
    猜你喜欢
    • 2018-01-20
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2017-04-08
    • 1970-01-01
    • 2019-11-19
    • 2018-03-03
    相关资源
    最近更新 更多