我想在react-router中添加hash到我的endopints以防止来自服务器的错误响应。 我正在使用python -m SimpleHTTPServer -p 8888
来创建服务器。
这个简短的示例工作,但是当我试图在某些航线重新加载页面像/about
然后我得到一个错误: Error response Error code 404. Message: File not found. Error code explanation: 404 = Nothing matches the given URI.
Error response Error code 404. Message: File not found. Error code explanation: 404 = Nothing matches the given URI.
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
const Routes = () => (
<Router>
<div>
<ul>
<li><Link to="/about">About Link</Link></li>
<li><Link to="/company">Company Link</Link></li>
</ul>
<Switch>
<Route path="/about" component={About} />
<Route path="/company" component={Company} />
</Switch>
</div>
</Router>
);
class App extends React.Component {
render() {
return (
<Routes />
);
}
}
有两种方法可以解决它:
1)使您的Web服务器始终使用相同的index.html
文件进行响应,无论路由如何。 这将防止404错误,但不完美,因为它不支持浏览器缓存
2)使用HashRouter - 它将UI路由保留在URL的哈希部分,这不应该使服务器返回404并且将启用浏览器端缓存。 这种方法的缺点是您不能使用#target链接到网页的特定部分
我没有好好看文档,下面有解决方案:
const Routes = () => (
<HashRouter basename="/#">
<div>
<ul>
<li><Link to="/about">About Link</Link></li>
<li><Link to="/company">Company Link</Link></li>
</ul>
<Switch>
<Route path="/about" component={About} />
<Route path="/company" component={Company} />
</Switch>
</div>
</HashRouter>
);