React Native Expo部署Firebase后子路径访问出现404错误
解决Expo Web部署到Firebase Hosting后的路由404问题
问题本质
你的Expo Web应用是单页应用(SPA),本地开发时Dev Server会自动将所有路由请求转发到index.html,但Firebase Hosting默认是静态文件服务器,直接访问/cancer或/chemo这类子路径时,会尝试查找对应物理文件,找不到就返回404。
解决方案
1. 配置Firebase Hosting重写规则
修改项目根目录下的firebase.json,在hosting节点添加rewrites规则,将所有请求重定向到index.html:
{ "hosting": { "public": "src/main/www", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "**", "destination": "/index.html" } ] } }
这个规则让Firebase不管收到什么路径的请求,都返回根目录的index.html,交由React Navigation处理前端路由。
2. 修正NavigationContainer的前缀配置
确保prefixes包含生产环境的HTTPS域名(Firebase Hosting默认启用HTTPS):
<NavigationContainer linking={{ prefixes: ['http://localhost:8081', 'https://cancer-hacked.web.app'], config: { screens: { CancerHomepageWeb: 'cancer', ChemoHomepageWeb: 'chemo' } } }}>
3. 简化部署脚本(可选)
手动移动文件容易出错,直接指定Expo导出目录为Firebase的public目录:
npx expo export -p web --output-dir src/main/www firebase deploy
这样无需手动复制文件,直接覆盖到目标部署目录。
4. 检查组件导入(重要)
你的index.js中使用了CancerHomepageWeb和ChemoHomepageWeb但未导入,需补充导入语句:
import CancerHomepageWeb from './path/to/CancerHomepageWeb'; // 替换为实际文件路径 import ChemoHomepageWeb from './path/to/ChemoHomepageWeb'; // 替换为实际文件路径
验证部署
修改完成后重新执行部署命令,访问https://cancer-hacked.web.app/cancer或https://cancer-hacked.web.app/chemo即可正常加载对应页面。
内容的提问来源于stack exchange,提问作者MattJ
相关产品推荐
相关产品推荐

