【问题标题】:How do I Serve a 404 page using firebase hosting for a React SPA?如何使用 Firebase 托管为 React SPA 提供 404 页面?
【发布时间】:2016-12-13 13:59:19
【问题描述】:

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

【问题讨论】:

  • 我希望您的 firebase.json 包含 "source": "**" 重写,这意味着您正在重写所有 URL 到您的主页。 Firebase Hosting 不知道您正在使用 react-router,因此它无法检测到不匹配的路由。所以你必须在你的客户端 react-router 配置中添加一个 default/catchall 路由。这看起来很有希望:stackoverflow.com/questions/32128978/…
  • 您可以分享有关路由器设置方式的任何代码吗?

标签: reactjs firebase redux react-router firebase-hosting


【解决方案1】:

您可以使用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 显示未找到消息。

【讨论】:

    【解决方案2】:

    您可以让 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 route (*) 应该是最后一个,以便 React Router 可以尝试所有其他路由并最终到达此位置。

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

    【讨论】:

    • 但请注意,这不会响应 HTTP 404。如果您需要正确的 HTTP 状态代码,则必须使用 Michael Bleigh 建议的微调重写规则
    猜你喜欢
    • 2018-10-18
    • 2018-01-22
    • 2021-01-29
    • 1970-01-01
    • 2020-09-22
    • 2021-10-17
    • 2019-05-23
    • 2020-11-12
    相关资源
    最近更新 更多