【问题标题】:Next.js Firebase Hosting 404 error on all except index.htmlNext.js Firebase Hosting 404 错误除了 index.html
【发布时间】:2021-05-31 02:01:01
【问题描述】:

我用npm run build && npm run export 构建了一个nextjs 应用程序,并使用firebase deploy 命令部署到了firebase。在此之前,我在我的项目文件夹中使用了firebase init,只使用了默认选项,例如。不是单页应用程序。

然而,当我在 firebase 提供的 url 中访问我的项目后,我看到主页是 index.html,但每当我使用任何其他 slug 时,它都会抛出 404。为什么会这样?我已经包含了我的 firebase.json 文件,以防万一。

firebase.json

  "hosting": {
    "public": "out",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

【问题讨论】:

    标签: reactjs firebase next.js


    【解决方案1】:

    根据您的 Firebase 托管规则,您可以提供用户请求的确切文件。

    要将其他/所有 URL 重写为您的 index.html,您需要将 rewrite rule 添加到您的 firebase.json。单页应用程序的典型重写规则可能如下所示:

    "hosting": {
      // ...
    
      // Serves index.html for requests to files or directories that do not exist
      "rewrites": [ {
        "source": "**",
        "destination": "/index.html"
      } ]
    }
    

    【讨论】:

    • 谢谢你的回答,但这其实不是spa,你知道在nextjs构建多页webapp的情况下应该怎么做吗?
    • 啊,这是对 Cloud Functions 或 Cloud Run 的重写。如果你在我提供的文档链接上向下滚动一点,也有这样的例子。
    • 嘿@MelihAlan 你用这个有什么收获吗?
    • 我做到了,但我意识到我从一开始就做错了!因为 NextJs 是一个 SSR 框架,所有路由(页面)都将在服务器中呈现,这就是为什么我上传了一个名为 server.js 的文件,其中包含一个云函数(在 firestore 云函数中运行),它处理所有路由。这解决了问题。我是新手,所以我无法理解您所指的文档,如果这与您的答案相同,请告诉我,以便我接受您的答案。再次感谢。
    • 确实是一样的:您的 server.js 在常规 Cloud Fuctions/Express 应用程序中提供与 index.js 相同的功能。
    【解决方案2】:

    对于希望将静态导出的 Next.js 应用部署到 Firebase 托管的所有人:

    您必须像这样在 firebase.json 中的托管配置中添加 "cleanUrls": true :

    "hosting": {
        "public": "build",
        "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
        "cleanUrls": true,
        "rewrites": [
          {
            "source": "**",
            "destination": "/index.html"
          }
        ]
      },
    

    如果没有“cleanUrls”配置,用户将不得不导航到 https://example.com/login.html 以便 Next.js 路由到例如登录页面。使用该参数,可以向https://example.com/login 发出网络请求。

    【讨论】:

    • 在静态生成/导出的 Next.js 应用程序上为我工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2021-01-13
    • 2021-02-20
    相关资源
    最近更新 更多