react-router-dom 在直接访问 URL 时生成 404,但不在开发中

IT技术 reactjs react-router react-router-dom
2021-05-02 04:39:46

我有一个使用 create-react-app 创建的 react 应用程序,并且正在使用 react-router-dom 进行路由。

总体布局为:

应用程序.js

<BrowserRouter>
    <BodyContent />
</BrowserRouter>

正文内容.js

        <Fragment>
            <Navigation/>
            <main>
                <ScrollToTopRoute path="/" exact component={HomePage}/>
                <ScrollToTopRoute path="/page1" exact component={Page1}/>
                    <ScrollToTopRoute path="/page1/page2" exact component={Page2}/>
                <ScrollToTopRoute path="/page3" exact component={Page3}/>
               ... etc...


            </main>
        </Fragment>

ScrollToTopRoute 只是标准路由器功能的扩展,可确保新页面滚动回顶部以获得良好的用户体验。

滚动到顶部.js

import React, { Component } from 'react';
import { Route, withRouter } from 'react-router-dom';
import ReactGA from 'react-ga';
ReactGA.initialize('UA-5477132-2');



class ScrollToTopRoute extends Component {
    componentDidUpdate(prevProps) {
        if (this.props.path === this.props.location.pathname && this.props.location.pathname !== prevProps.location.pathname) {
            window.scrollTo(0, 0);
            ReactGA.pageview(window.location.pathname + window.location.search);
            console.log("Triggered");
        }
    }

    render() {
        const { component: Component, ...rest } = this.props;

        return <Route {...rest} render={props => (<Component {...props} />)} />;
    }
}

export default withRouter(ScrollToTopRoute);

在开发过程中,应用程序按预期工作,所有路由都可以正常工作,如果您直接转到类似的 URL localhost:3000/page1,它将正确加载。我已经使用 yarn build 构建了站点并部署到典型的 VPS。网站和组件/路由的内部链接都按预期工作,但是当直接访问 URL 时,例如www.theurl.com/page1404,我不知道为什么结果不同。

2个回答

我相信这的根本原因实际上是由于您的服务器的配置方式。

React Router只能在您的前端脚本加载后(从索引页面)处理路由,当用户/foo在生产中点击深度链接路由时,情况并非如此

你必须设置你的服务器上每个路由请求返回索引页,除了API需要由服务器处理的路线。

这应该设置你的服务器让 React Router 处理深层链接请求。

如果您使用 Node 和 Express,它应该如下所示:

app.get('*', function (req, res) {
  res.send('public/index.html')
})

如果我能进一步解释,请告诉我。

我也面临同样的问题。通过添加具有以下内容的 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>

在以下位置找到了解决方案:How to fix "404" error when directly access a component in react