【问题标题】:How to redirect 404 page inside an axios service - nextjs如何在 axios 服务中重定向 404 页面 - nextjs
【发布时间】:2022-01-22 21:10:47
【问题描述】:

我正在使用 axios。 当我收到我的 api 的响应时,我想检查状态。 例如我想重定向到 404 页面。

const api = axios.create({
  headers: {
    common: {
      'Content-Type': 'application/json'
    },
    post: {

    }
  }
});
api.interceptors.response.use(
  ...

  (error) => {
const code = parseInt(error.response && error.response.status)
     if (code === 404) {
          console.log("responsive",error)
          if(data){
            data.forEach(itemError => {
              toast.error(itemError, {
                theme: 'colored',
              });
            });
          }else{
            //redirect to 404 page. but it doesn't work. 
            //return window.location.href = '/404';
          }
...

但我不知道如何在其中重定向。

【问题讨论】:

    标签: javascript axios next.js


    【解决方案1】:

    检查useRouter钩子https://nextjs.org/docs/api-reference/next/router

    在你的功能组件中初始化路由器。

    const router = useRouter();
    

    然后重定向到任何页面

    router.push('your-page')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多