下一个动态路由 404 firebase 托管

Mar*_*mes 10 javascript firebase reactjs firebase-hosting next.js

使用部署在 firebase 上的 next.js 应用程序。

我已经部署了该应用程序并使用了一段时间。

  1. 我创建了一个动态路线页面
  2. 再次部署应用程序
  3. 我可以通过路由器访问动态页面,但是一旦刷新页面,我就会收到 404 页面未找到

我尝试过但不起作用的解决方案:

  • 使用dynamicLink true 进行重写
  • 将目的地重写为动态路由和正则表达式/源
"rewrites": [
      {
        "source": "/job/**",
        "destination": "/job/[jobId]/index.html"
      }
Run Code Online (Sandbox Code Playgroud)
  • cleanUrls true
  • TrailingSlash:true 加上重写配置,目标为动态页面
  • 还有更多吗

我找到了很多解决这个问题的方法,但没有一个不适合我。

任何想法?

firebase.json 文件:

{
  "hosting": {
    "public": "out",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "cleanUrls": true,
    "rewrites": [
      {
        "source": "**",
        "destination": "out/index.html"
      }
    ]
  },
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ],
      "predeploy": ["npm --prefix \"$RESOURCE_DIR\" run build"]
    }
  ]
}

Run Code Online (Sandbox Code Playgroud)

may*_*513 4

要使动态路由发挥作用,您必须使用服务器功能。您可以使用 Firebase 的实验框架功能。

结账 - https://firebase.google.com/docs/hosting/nextjs

如果没有服务器功能,Next.js 高级(动态)路由将无法工作。

按着这些次序:

  1. 删除现有的 Firebase 文件和文件夹等。firebase.json.firebase更新 firebase cli。
  2. 启用 Web 框架预览:firebase experiments:enable webframeworks
  3. firebase init hosting在 Next.js 应用程序的根目录中运行并按照提示操作。
  4. 跑步firebase deploy

确保您已激活付费计划,以便可以通过 firebase-cli 创建功能。

选项 2:工作示例

尝试以下

  1. 将所有路由重写到索引页
"rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
Run Code Online (Sandbox Code Playgroud)
  1. 将以下代码添加到您的索引路由
...
const router = useRouter();

useEffect(()=>{
    if(location.pathname !== "/")
        router.push(location.pathname)
}, [])
...
Run Code Online (Sandbox Code Playgroud)

查看此存储库以获取工作示例 - 工作示例 尝试导航到https://byte-ceps.web.app/aboutOrAnything

改善用户体验

// pages/index.jsx
import { useRouter } from "next/router";
import styles from "@/styles/Home.module.css";
import { useEffect } from "react";

export default function () {
  const router = useRouter();

  useEffect(() => {
    if (location.pathname === "/") router.push("/home");
    else router.push(location.pathname);
  }, []);

// you can create custom loading animation / splash screen here
  return (
    <div>
      <main className={styles.main}>
        <h1> Loading... </h1>
      </main>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

将您的目标网页移至/home

选项 3:

在 vercel.com 上部署 只需创建一个 vercel 帐户并将其链接到您的 GitHub。创建项目,选择您的 GitHub 存储库并根据需要设置任何机密。你完成了。

如果您想要拥有 .web.app 域,则需要从 Firebase 站点重定向到 vercel 部署或使用 iframe。但如果您已经购买了自己的域名,则只需设置 cname 条目即可完成部署。

更新

另外,在您firebase.json共享的问题中,重写应该是 to/index.html而不是out/index.html