我的堆栈是 React/Redux 作为前端,React Router v4 和 Firebase Hosting 作为后端。
和许多其他人一样,当用户刷新根 URL 以外的页面(如 https://example.com/about 或手动输入 URL https:/ 时),我也遇到了找不到 404 页面的问题/example.com/about.
我研究了很多网站,HashBrowser 似乎是解决这个问题的方法,但它不是一个完整的解决方案。它不会将用户带到正确的页面,而是呈现根 URL 组件。还不够好。在生产环境中使用historyApiFallback: true似乎也是一个坏主意。
我看到了这个包,connect-history-api-fallback,但它似乎是一个快速应用程序。
如何在使用 Firebase 托管我的网站时在我的 React 应用程序中实现此包? 或者还有其他解决办法吗?
我找到了解决方案。这仅适用于部署 React App、使用 Firebase Hosting 托管单页应用程序的人员。 (也应该适用于 Angularjs/Vuejs)
当您第一次运行
firebase init
时,他们会询问您是否要配置为单页应用程序,请确保选择yes。最终结果是他们会将这部分写入您的 firebase.json 文件,
"rewrites": [ {
"source": "**",
"destination": "/index.html"
}
它的作用与拥有
相同devServer: {
historyApiFallback: true
},
在 webpack.config.js 文件中将所有 URL 重定向到应用程序的根 URL。 (“/”)
firebase.json 文件的完整实现可能如下所示,
{
"hosting": {
"public": "public",
"rewrites": [{
"source": "**",
"destination": "/index.html"
}],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
更多信息可以在Firebase部署配置文档中找到。