react-router-dom 在直接访问 URL 时生成 404,但不在开发中 [英] react-router-dom Build Giving 404 When Accessing URL Directly, But Not In Development

查看:22
本文介绍了react-router-dom 在直接访问 URL 时生成 404,但不在开发中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

总体布局是:

App.js

<正文内容/></BrowserRouter>

Bodycontent.js

 <片段><导航/><主要><ScrollToTopRoute path="/" 精确组件={HomePage}/><ScrollToTopRoute path="/page1" 精确组件={Page1}/><ScrollToTopRoute path="/page1/page2" 精确组件={Page2}/><ScrollToTopRoute path="/page3" 精确组件={Page3}/>... 等等...</main></片段>

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

ScrollToTop.js

import React, { Component } from 'react';导入 { Route, withRouter } from 'react-router-dom';从'react-ga'导入ReactGA;ReactGA.initialize('UA-5477132-2');类 ScrollToTopRoute 扩展组件 {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("触发");}}使成为() {const { 组件:组件,...rest } = this.props;return <Route {...rest} render={props =>(<Component {...props}/>)}/>;}}导出默认 withRouter(ScrollToTopRoute);

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

解决方案

我认为造成这种情况的根本原因实际上是由于您的服务器的配置方式.

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

您必须将服务器设置为在每个路由请求上返回索引页除了api 需要由服务器处理的路由.>

这应该将您的服务器设置为让 React Router 处理深层链接请求.

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

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

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

I have a react app created with create-react-app and am using react-router-dom for routing.

The general layout is:

App.js

<BrowserRouter>
    <BodyContent />
</BrowserRouter>

Bodycontent.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>

The ScrollToTopRoute is simply an extension of the standard router functionality that ensures new pages scroll back to the top for a good UX.

ScrollToTop.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);

In development the app works as expected, all routes work and if you go directly to a URL like localhost:3000/page1 it will load correctly. I have built the site using yarn build and deployed to a typical VPS. The website and internal links to components/routes all work as expected, however when accessing a URL directly as above such as www.theurl.com/page1 it will 404 and I am at a loss as to why the outcome is different.

解决方案

I believe the underlying reason for this is actually due to how your server is configured.

React Router can only handle routing after your front-end scripts have been loaded (from the index page), which isn't the case when a user hits the /foo deeplink route in production.

You'll have to set your server up to return the index page on every route request except for api routes that need to be handled by the server.

This should set your server up to let React Router handle deeplink requests.

If you're using Node and Express it should look something like this:

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

Let me know if I can explain further.

这篇关于react-router-dom 在直接访问 URL 时生成 404,但不在开发中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆