React Error刷新时未在此服务器上找到请求的URL



我的React应用程序在本地运行良好,但当我部署它时,路由无法正常工作。当我点击导航栏按钮时,一切都很好,但当我尝试手动刷新或写入路线时,我会收到消息";在这个服务器上找不到请求的URL";。它还说";此外,在尝试使用ErrorDocument处理请求时,还遇到了404 Not Found错误&",即使我有.htaccess文件。

这是我的代码:

-这是导航栏中的一个按钮:

<Link to="/contact">
<button>
<FadeIn delay={200}>CONTACT</FadeIn>
</button>
</Link>

-这是App.tsx文件,其中包括路由:

import {BrowserRouter as Router, Route, Switch} from "react-router-dom"; 
function App() {
return (
<Router>
<Header />
<Switch>
<Route exact path = "/" component={Carusel}/>
<Route exact path = "/contact" component={Contact}/>
</Switch>
<Footer />
</Router>

);}

听起来您的服务器除了"/"之外没有处理任何路由,这在您路由客户端时很好,但向GET "/contact"发出请求将失败。

例如,React应用程序在网站配置中作为AWS S3 bucket上传时,需要设置错误文档。你可以将这个错误文档设置为你的index.html,这样404将由你的前端应用程序处理,它知道如何处理路由。

下面是一个错误文档设置为index.html的示例https://andela.com/insights/how-to-deploy-your-react-app-to-aws-s3/

请使用以下代码更新.htaccess文件,然后重试。

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>

最新更新