直接访问 Next.js 中的动态路由和 Github Pages 等静态托管网站会出现 404

问题描述 投票:0回答:3

我正在 Next.js 中编写我的 Web 应用程序,并将其托管在 Github Pages 上(外部限制,个人会使用 Vercel 或其他东西)。

我有一条动态路线:

webapp.com/experiments/[id]

每当用户创建实验时,ID 都需要动态生成,因此我无法预加载所有 ID 来构建静态页面。

重要的是这些页面能够动态生成,而不需要重新构建/重新部署项目。

localhost
上,我可以转到我的页面,它能够检索数据并将其显示在页面上。

但是,一旦我将其托管到 Github Pages 上,我就可以单击该页面并且它将加载,但当我尝试直接访问该 URL 时,它会给我一个 404。

我已经设置了

getStaticPaths
getStaticProps
,它构建了已知页面,但是当我转到新实验的 URL 时,它仍然给我一个 404。

我错过了什么? 有其他方法吗?

export async function getStaticPaths() {
  // Fetch initial list of experiment IDs from your database
  const experimentIds = await fetchExperimentUrls();

  // Generate paths for static generation
  const paths =
    experimentIds.urls.map((url: string) => ({
      params: { url: url.toString() },
    }));

  return {
    paths,
    fallback: true, 
  };
}

export async function getStaticProps({ params }: any) {
  const { url } = params;
  const res = await fetch(
    `${process.env.NEXT_PUBLIC_API_URL}/experiments/${url}`,
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    }
  );
  const experimentProps = await res.json();
  return {
    props: {
      experimentProps,
    },
    revalidate: 60, // Optional: Set a revalidation time (in seconds) to update the static page
  };
}
reactjs next.js github-pages
3个回答
1
投票

当我发表评论时,我错过了你问题的重要部分。您正在动态渲染一些页面,但正在部署静态资产。 Github Pages 不运行 Next 服务器,它假设您正在部署静态页面(所有这些页面都已构建)。托管在 gh-pages 上的网站无法动态获取服务器端数据,因为没有服务器。如果需要获取新实验,您需要将您的应用程序托管在 VPS 或云提供商上。


0
投票
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

export default function ExperimentPage() {
  const router = useRouter();
  const [experimentProps, setExperimentProps] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const res = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/experiments/${router.query.id}`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
          },
        }
      );
      const data = await res.json();
      setExperimentProps(data);
    }
    if (router.query.id) {
      fetchData();
    }
  }, [router.query.id]);

  if (!experimentProps) {
    return <div>Loading...</div>;
  }

  return (
    <div>...</div>
  );
}

0
投票

我最近遇到了同样的问题。我的解决方案是使用 React JS 和哈希路由器重写我的代码。所以路线就变成了https://example.com/#/whatever_routes

© www.soinside.com 2019 - 2024. All rights reserved.