【问题标题】:SPA 404 on Refresh: Go+React App on HerokuSPA 404 刷新:Heroku 上的 Go+React 应用程序
【发布时间】:2021-02-21 14:53:41
【问题描述】:

我在 Heroku 上看到一个问题,我在本地没有遇到问题。我看过各种文章和其他解决此问题的 SO 帖子,我了解到这与在我的应用程序中正确配置 static.json 文件有关,以便 heroku 正确处理前端反应路由,但我在解决这个问题时遇到了一些真正的麻烦。

  • 我正在使用以下构建包,并确认它们是通过 Heroku 仪表板 > 设置安装的:

  • https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku-community/static.tgz

  • https://github.com/mars/create-react-app-buildpack

  • 使用gin-gonic 服务器并提供./web 服务于我的.Dockerfile 指定的前端

  • 我有以下 static.json:

{
    "root": "build/",
    "routes": {
        "/**": "index.html"
    },
    "clean_urls": false,
    "https_only": true,
    "headers": {
        "/**": {
        "Strict-Transport-Security": "max-age=31557600"
        }
    }
}
  • 我的项目结构如下:
/app
- /main.go
- /server
-- /server package .go files...
- /client
-- /public
-- /src
-- /remaining react related files and assets...

我尝试在应用程序根目录和client 目录中添加static.json 文件,但均无济于事。如果我刷新或从外部网站导航到主页以外的任何内容,仍然会看到 404。

【问题讨论】:

    标签: reactjs go heroku react-router


    【解决方案1】:

    因此,我在研究此问题时发现的所有 static.json 解决方案似乎都不起作用。据我所知,这似乎是 react 路由和/或 Heroku 的一个已知问题。

    话虽如此,如果这对遇到此问题的其他人有帮助,我就是这样解决的:

    1. 在服务器上设置 NotFound 处理程序:

      所有 NotFound 处理程序所做的只是为您的 index.html 文件提供服务允许您的 SPA 框架自行处理路由(确定是否有效或确实未找到)。

      我在 go/gin-gonic 中通过以下方式实现了这一点:

      e := gin.New()
      // gin engine set up...
      
      e.NoRoute(func(ctx *gin.Context){
          ctx.File("./web")
      })
      

      原因 - 当您正常点击您的应用程序(通过基本 url)时,您的应用程序将提供 index.html,然后来自应用程序内的后续点击通过 SPA 路由处理。但是,如果您直接导航到任何其他路由(即手动转到地址栏中的https://<your domain>.com/foo),您将绕过 SPA 路由并直接转到服务器。这种情况也可以通过简单地刷新除主页以外的任何页面来实现。

      因此,当您在服务器上点击未找到时提供 index.html,您重新启用 SPA 框架以发挥其魔力并提供该路线 如果它是有效的,这是我们想要的,但也能够通过...处理 404

    2. 在 React 应用程序中连接 NotFound 组件:

      我在 React 中实现了这一点,方法是制作一个简单的组件并连接一个 Route 以在定义所有其他路由后将其注册到 path="*" 作为 catch all 来使用它:

      <Router basename="/">
          <Route exact path="/foo">
              <FooView />
          </Route>
          <Route exact path="/">
              <HomeView />
          </Route>
          <Route path="*">
              <NotFoundView />
          </Route>
      </Router>
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-07
      • 2021-01-08
      • 2020-10-16
      • 2020-06-06
      • 2021-03-01
      • 1970-01-01
      • 2020-04-16
      • 2021-07-11
      相关资源
      最近更新 更多