我部署了一个作为主页的Github的React应用程序。
问题是我不能直接访问/home或任何子域,也不能刷新页面。扔404。但是,在应用程序内部重定向是有效的,如果你等待,因为动画是在登陆页面上完成的,你可以到达/home。
我检查了一下,没有其他在/home下注册的存储库。
谁能告诉我原因吗?我该如何解决这个问题呢?
更新: React路由器配置如下:
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Preloader from './components/Preloader';
import Home from './components/Home';
import './App.scss';
class App extends Component {
render() {
return (
<Router>
<React.Fragment>
<Switch>
<Route path="/" exact component={Preloader} />
<Route path="/home" component={Home} />
</Switch>
</React.Fragment>
</Router>
);
}
}
export default App;发布于 2019-11-23 23:32:28
解决方案1
如本文所示,部署,并将其路由到Github页面应该使用HashRouter来避免在刷新页面时在GitHub页面上出现404错误。
根据HashRouter文档的说法:
HashRouter 路由器,它使用URL的散列部分(即window.location.hash)来保持UI与URL的同步。 重要注意事项:哈希历史不支持location.key或location.state。在以前的版本中,我们试图避免这种行为,但是有一些我们无法解决的边缘问题。任何需要这种行为的代码或插件都不能工作。由于此技术仅用于支持遗留浏览器,因此我们鼓励您配置您的服务器以供使用。
尝试用以下方式更新导入语句:
import { HashRouter as Router, Switch, Route } from "react-router-dom";解决方案2
更好的解决方案可能是配置服务器以正确处理路由。请查看这个指南,它展示了如何使用express实现这个功能:
const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
// serve static assets normally
app.use(express.static(__dirname + '/public'))
// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(port)
console.log("server started on port " + port)https://stackoverflow.com/questions/58631182
复制相似问题