问题描述:当您在新的环境中部署React应用时,React路由器dom可能不会正常工作。您可能会看到如下错误消息:'Cannot GET /route”。这是因为在部署时,服务器会尝试查找具有此路径的静态文件,而不是等待React路由器处理该路径。
解决方案:
例如,如果您的应用程序将在'https://example.com/my-app”上托管,则应'homepage”属性设置为'/my-app/”。
"homepage": "/my-app/",
BrowserRouter使用HTML5 history API来处理路由,而HashRouter不使用此API。这可以防止错误消息'Cannot GET /route”出现。在您的代码中使用BrowserRouter替换HashRouter。
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
如果您使用的是Node.js和Express,则需要添加以下代码:
app.get('/*', (req, res) => { res.sendFile(path.join(__dirname, 'path-to-index.html')); });
这将确保在请求React应用中的任何路由时,服务器都会返回index.html文件,以便React路由器可以处理路由。
如果您使用的是Apache服务器,请确保已启用mod_rewrite模块和托管您的静态资源。如果您使用的是Nginx服务器,请确保正确配置了location指令。
参考资料:
https://create-react-app.dev/docs/deployment/#serving-apps-with-client-side-routing
https://dev.to/aurelkurtula/deploying-a-react-app-to-github-pages-with-react-router-4-42np
上一篇:部署后缺失Vite的清单文件
下一篇:部署后React项目无法工作