React生产环境路由器在深度刷新Firebase后出现404错误

23

我在我的index.js文件中拥有这些路由。

 <Router history={customHistory}>
        <div className="row">
            <Switch>
                <Route exact path="/login" component={Login}/>
                <Route path="/home" component={Home}/>
                <Route path="/politicas" component={Policies}/>

                <Redirect exact from="/" to="/login"/>
                <Route exact path="*" status={404} component={NotFound}/>

            </Switch>

        </div>
    </Router>

在本地环境中一切正常,但我有一个Firebase应用程序,在部署我的Firebase项目时,我使用:

npm run build

firebase deploy

但在Firebase应用程序中进行深度刷新后返回404,唯一有效的路径是“ / ”。我该怎么做才能让所有路径始终正常工作?


非常感谢!!我以为是React的问题,我找了好几天。 - Abel Olguin Chavez
1个回答

74

我回答自己,需要将以下内容添加到firebase.json文件中。

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

1
Firebase有自己的服务器,当您导航到 /something 时,服务器会认为该路径中存在一个目录或文件,因此,当您像我在示例中所示地重写firebase.json文件时,所有流量都将转到index.html文件,而React路由器则接管所有这些流量。 - Abel Olguin Chavez
感谢您抽出时间发布您的解决方案。 - Richard Bonneau
这仍然返回状态码 200,而不是应该的 404。你有什么想法如何解决? - Vlad
嘿,感谢你回来并发布这个解决方案。我都快抓狂了。你的答案解决了所有问题。 - skypen
非常好的答案,非常感谢!我在手动刷新React/Firebase应用程序时遇到了404错误,这个解决方法很快就解决了。非常棒的文章!! - rolandforbes
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接