我想在 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)