【问题标题】:404 returned on any URL accessed before accessing the home URL在访问主 URL 之前访问的任何 URL 上返回 404
【发布时间】:2018-10-27 02:49:31
【问题描述】:

我正在为我的应用程序使用 react-router,当我在服务器上部署它时,我注意到如果我在打开主 URL 之前请求任何 URL,它将返回 404。然后在访问主 URL 后,所有其他 URL 将工作正常!

index.tsx:

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
  ,
  document.getElementById('root') as HTMLElement
);

App.tsx:

public render()
  {
    return(
        <div className="App">
            <div className="row margin-auto">
                <Header/>
                <Main/>
            </div>
        </div>
    )
  }

Main.tsx:

public render()
    {
        return (
            <div id="main" className="col col-9-and-half no-padding-h vh-100">
                <div className="container-fluid no-padding-h">
                    <main>
                        <Switch>
                            <Route path='/home' component={Home} />
                            <Route exact={true} path='/' component={Home} />
                            <Route path="/matches" component={Matches} />
                            <Route path='/login' component={Login} />
                            <Route path='/sign-up' component={SignUp} />
                            <Route path='/contact-us' component={ContactUs} />
                        </Switch>
                    </main>
                </div>
            </div>
        )
    }

例如,当我尝试打开 www.mywebsite.com/sign-up 时,它会返回 404,但如果我先打开 www.mywebsite.com,然后尝试访问 www.mywebsite.com/sign-up,它会返回工作正常。

【问题讨论】:

  • 您能否分享一下您用于提供静态文件的内容以及您的 index.html 的外观?使用 react 路由器时,您应该将 404 重定向到您的 index.html,以便 react 可以初始化并让 react-router 处理从那里渲染正确的路由。

标签: reactjs react-router react-router-dom


【解决方案1】:

您的服务器中似乎没有重定向设置。要使单页 JavaScript 应用程序正常工作,您必须确保您的服务器为您的 index.html 提供所有路径。

需要注意的一点是,您必须在 react-router 内管理 404 处理。这可以通过在路由定义的末尾添加不带path 属性的&lt;Route /&gt; 来实现。重要的是它位于末尾,以便在显示 404 之前用尽所有可能的路线

<Switch>
  <Route path='/home' component={Home} />
  <Route exact={true} path='/' component={Home} />
  <Route path="/matches" component={Matches} />
  <Route path='/login' component={Login} />
  <Route path='/sign-up' component={SignUp} />
  <Route path='/contact-us' component={ContactUs} />
  <Route component={NotFound} />
</Switch>

【讨论】:

    【解决方案2】:

    感谢 SethWilliam Chou 指导我回答问题,我做了以下 htaccess 配置来处理请求,现在一切似乎都正常:

    <ifModule mod_rewrite.c>
        RewriteEngine On
    
        RewriteBase /
    
        RewriteRule ^index\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
    
        RewriteRule . /index.html [L]
    </ifModule>
    

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 2017-06-04
      • 1970-01-01
      相关资源
      最近更新 更多