Rey*_*nor 4 typescript axios next.js
我想在 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)
如果没有看到getServerSideProps或getStaticProps的实际实现,很难给出答案,但这可能会有所帮助。您的拦截器可能应该抛出一个自定义错误,您可以在这些方法中识别该错误,然后使用Next.js 重定向
// 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);
}
Run Code Online (Sandbox Code Playgroud)
然后,在数据获取方法中(需要适配Typesctipt):
export async function getServerSideProps(context) {
try {
await customAxios.get(...)
} catch(e) {
if (e instanceof CustomError){
return {
redirect: {
destination: '/503'
}
};
} else {
//...
}
}
//...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5559 次 |
| 最近记录: |