如何使用 firebase 托管为 React SPA 提供 404 页面?

How do I Serve a 404 page using firebase hosting for a React SPA?

我目前正在为我的单页 React 应用程序使用 firebase 托管。我还在我的 public 目录中添加了一个 404.html 页面。我的假设是,如果用户输入不在我的路由中的 url(使用 react-router),该页面将得到服务,但 firebase 无法知道 url 是否有效或不,或在那里。目前,如果我在我的主应用程序 url 的 / 之后随机输入一些内容,该页面只会显示空白。这是我需要在我的 React 应用程序中考虑的事情吗?如果是的话,如何?

您可以让 React Router 负责在客户端提供 404 页面。您可以这样设置:

var NotFound = React.createClass({
    render: function() {
        return (<h1>Page Not Found</h1>);
    }
});

var App = React.createClass({
    render: function() {
        <Router history={browserHistory}>
            <Route path="/" component={App}>
                <Route path="first" component={SomeComponent}/>
                <Route path="second" component={SomeOtherComponent}/>
                <Route path="*" component={NotFound}/>
            </Route>
        </Router>
    }

}); 

请注意,catch all 路由 (*) 应该是最后一个,以便 React Router 可以尝试所有其他路由并最终到达此路由。

Here's 一篇很好的文章解释了这一点。

您可以使用 firebase.json 配置部分解决此问题,但由于 Firebase 托管仅提供静态内容,因此您必须处理 JavaScript 中的一些逻辑。一个简单的包罗万象的样子:

{
  "hosting":{
    "rewrites":[{"source":"**","destination":"/index.html"}]
  }
}

但是,您可以创建更具体的重写以匹配应用程序的路由结构,例如:

{
  "hosting":{
    "rewrites":[
      {"source":"/users/*","destination":"/index.html"},
      {"source":"/account","destination":"/index.html"},
      {"source":"/posts/*","destination":"/index.html"},
    ]
  }
}

在上面的示例中,/users/foo 将路由到 /index.html,但 /unknown/url 将路由到 404.html

以上只是让您完成了一部分,但不知道您的实际应用程序数据。如果 /users/foo 不是有效的用户名,您需要在 /index.html.

中使用 JavaScript 显示未找到消息