我有一个 React 应用程序,它使用 React-router 和一个看起来像这样的路由器:
<Router>
<div>
<Route exact path="/" component={Homepage} />
<Route path="/map/:uid" component={Userpage} />
<Footer />
</div>
</Router>
该应用程序使用 Firebase 托管进行托管。
如果我打开我的网站并单击,路由器将我带到/map/uid,它加载得很好。但是,如果我关闭浏览器,然后尝试显式导航到
<domain>/map/<known uid>
,我会从 Firebase 收到“未找到页面”页面。这是我第一次使用react-router。
更新#1
我已将我的
firebase.json
更新为:
{
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
我不再收到“页面未找到”页面;但是,我的反应应用程序的内容永远不会加载,并且我在控制台中注意到一个错误:
Uncaught SyntaxError: Unexpected token <
更新#2
我现在明白为什么会出现错误。查看 Chrome 开发工具中的 Sources 选项卡,只有当我直接导航到
static/css
时,我的 static/ 文件夹才有一个奇怪的名称(static
而不是 /map/{known uid}
)。当我导航到主页时,所有加载都正常。
这解释了错误。我还是不知道如何解决。
对我来说,我可以看到根 url,但其他路由(例如“/pricing”)给了我 404。我将其添加到我的 firebase.json 文件中,现在它可以工作了。还要确保 firebase/auth 允许在域上工作。 firebase 的 auth 部分有一个设置。
"rewrites": [ {
"source": "**",
"destination": "/index.html"
}],
我的完整 firebase.json
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"hosting": {
"public": "build",
"rewrites": [ {
"source": "**",
"destination": "/index.html"
}],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
},
"storage": {
"rules": "storage.rules"
}
}
迟到的答案,但我面临着同样的问题。我用两个步骤解决了这个问题:
{
"hosting": {
"site": "myproject",
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/">
.
.
.
迟到了,但请尝试从 package.json 中删除“homepage”键(或确保它相对于主页存储位置是正确的。
迟到的回答,但它解决了我的问题: 当执行
firebase init
时,它会询问是否是单页应用程序。默认答案是 No
,但是,只需选择 Yes
即可。
由于客户端路由,您会收到此错误。 (React 内心深处)
所以你可以做
<base href="/"/>
。尝试将
cleanUrls
属性设置为 true
。
请参阅 Firebase 文档了解更多信息
"hosting": {
// ...
// Drops `.html` from uploaded URLs
"cleanUrls": true
}
就我而言,问题有所不同。我能够正确地看到索引页,但当我导航到新路线时,我看到的是空白页。
Firebase 已正确配置:
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
部署后,我进入请求选项卡并看到了这一点。
然后我检查了
index.html
文件并注意到了这一点:
由于我的配置在同一个
dist
目录中构建所有内容,
dist/index.html
dist/main.bundle.js
...
这个问题很简单。我必须通过调整 webpack 配置来告诉 webpack 我的资源是否相对于
index.html
文件放置:
{
...
output: {
...
publicPath: '/',
...
}
...
}
现在需要像这样的文件:
这将告诉浏览器查看根目录,即放置
index.html
的位置。
如果您有多个配置并且不扩展它们,请确保更改生产配置。
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"cleanUrls": true
},
"rewrites": [
{
"source": "/(.*)",
"destination": "/index.html",
"dynamicLinks": true
}
]
}
在你的 firebase.json 中尝试一下这个,路由肯定可以工作
在
basename
中指定 Router
怎么样?沿着这个:
<Router basename='/map/5AJA3RefFuTZ8z4Gn6BjMgZRgPZ2'>