[英]React + TypeScript with router deployement issue on Github Pages
本地运行正常,但是在“ npm run deploy”上运行时,网站返回404。
我有一个React + TypeScript应用程序,它利用react-router-dom BrowserRouter在页面之间导航。
我知道带有react-router的github页面上的问题,因此我尝试添加basename = {process.env.PUBLIC_URL},将其更改为HashRouter,还有很多其他可能性。 我已经连续7个小时在这个问题上……而且对于Typescript来说,这个特殊问题似乎没有任何资源。
有人可以帮我!
index.tsx
ReactDOM.render(
<AppRouter />,
document.getElementById('root') as HTMLElement
);
Router.tsx
export const AppRouter: React.StatelessComponent<{}> = () => {
return (
<BrowserRouter basename={process.env.PUBLIC_URL}>
<div>
<NavBar />
<Switch>
<Route exact={true} path='/' component={App} />
<Route exact={true} path='/' component={Notes} />
<Route exact={true} path='/About' component={About} />
</Switch>
</div>
</BrowserRouter>
);
还尝试了Router.tsx
export const AppRouter: React.StatelessComponent<{}> = () => {
return (
<HashRouter>
<div>
<NavBar />
<Switch>
<Route exact={true} path='/' component={App} />
<Route exact={true} path='/' component={Notes} />
<Route exact={true} path='/About' component={About} />
</Switch>
</div>
</HashRouter>
);
NavBar.tsx
export const NavBar: React.StatelessComponent<{}> = () => {
return (
<div id='nav-bar'>
<AppBar position='static' color='default'>
<Toolbar>
<span id='navbar-title'>
<Typography variant='title' color='default'>
Keep
</Typography>
</span>
<Link to="/">
<Button size="large" color="primary" variant="text">Notes</Button>
</Link>
<Link to="/About">
<Button size="large" color="primary" variant="text">About</Button>
</Link>
</Toolbar>
</AppBar>
</div>
)
感谢您的阅读。
下面的EDIT是来自Web控制台的404错误的确切错误响应。 关于收藏夹图标,这可能是个问题吗? 位置完全错误
json469.github.io/:1 Refused to load the image 'https://json469.github.io/favicon.ico' because it violates the following Content Security Policy directive: "img-src data:".
我还尝试通过打印出process.env.PUBLIC_URL进行调试,但是它返回了一个空字符串...
下面的EDIT2是对Router.tsx进行的更改,已解决了该问题。
<HashRouter>
<div>
<NavBar />
<main>
<Switch>
<Route exact={true} path='/' component={App} />
<Route exact={true} path='/' component={Notes} />
<Route exact={true} path='/About' component={About} />
</Switch>
</main>
</div>
</HashRouter>
这不太可能是由于TypeScript-甚至是React Router。 如果收到404,那是因为如果用户访问服务器不知道的路由,则服务器必须将用户重定向到React应用,然后您的应用可以假装进行实际路由。
但是,似乎GitHub Pages不支持此功能。 因此,您不能执行“正确的” URL,例如username.github.io/page/some-route。 如您所提到的,一种解决方法是使用哈希路由器,但这意味着URL看起来像username.github.io/page#/some-route。
因此,您的问题可能是您正在尝试前一种方法,而不是后者。 因此,要解决该问题,您可以尝试这种路由,也可以移至其他主机。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.