Javascript 为什么反应路由器会抛出“无法获取/示例”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35104761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:17:03  来源:igfitidea点击:

Why is react router throwing 'Cannot GET /example' error?

javascriptreactjsreact-router

提问by Pablo

I'm learning React, and I need to add some routes with React Routes.

我正在学习 React,我需要使用 React Routes 添加一些路由。

I have installed react-routerwith npm install react-router.

我已经安装react-routernpm install react-router.

This is the main jswhere I have to declare the routes

这是main js我必须声明路线的地方

import React from 'react';
import {ReactDOM, render} from 'react-dom';
import App from './Components/AppComponent';
import Example from './Components/ExampleComponent';
import { Router, Route, IndexRoute, Link, IndexLink, browserHistory } from 'react-router'


render((
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <Route path="example" component={Example}/>
        </Route>
    </Router>
), document.getElementById('App'));

Navigating to /works fine. But when I go to /exampleI'm getting:

导航到/工作正常。但是当我去/example我得到:

Cannot GET /example

不能获取 /example

error

错误

What am I doing wrong?

我究竟做错了什么?

This way I have the same issue:

这样我有同样的问题:

<Router>
    <Route path="/" component={App} />
    <Route path="/example" component={Example}/>
</Router>

Example Component

示例组件

import React from 'react';

class Example extends React.Component {
    render(){
        return <div>Example</div>
    }
}

export default Example

This is the Link:

这是Link

<Link to={'/example'}>aa</Link>

There are no errors in console.

控制台中没有错误。

After the change I'm getting this errors in console (Caused by the Link)

更改后,我在控制台中收到此错误(由 引起Link

index.js (line 27585) Warning: [react-router] Location "/" did not match any routes

index.js (line 27585) Warning: [react-router] Routerno longer defaults the history prop to hash history. Please use the hashHistorysingleton instead. https://github.com/ReactTraining/react-router/blob/master/upgrade-guides/v2.0.0.md#no-default-history

index.js(第 27585 行)警告:[react-router] 位置“/”与任何路由都不匹配

index.js(第 27585 行)警告:[react-router]Router不再默认历史属性为哈希历史。请改用 hashHistory单身人士。https://github.com/ReactTraining/react-router/blob/master/upgrade-guides/v2.0.0.md#no-default-history

回答by RichG

Your example route is nested within your parent route so you should't need a /in /example.

您的示例路线嵌套在您的父路线中,因此您不需要/in /example

Also you can try setting an IndexRoutewith whatever your home component would be so that it has a reference.

您也可以尝试IndexRoute使用任何您的家庭组件设置一个,以便它有一个参考。

Linking to the route would probably help so you can see what is coming up in the URL to make sure its what your looking for.

链接到路由可能会有所帮助,因此您可以查看 URL 中出现的内容,以确保它是您要查找的内容。

Your App component shouldnt really be rendering anything other than {this.props.children}because that is where all the components that the router is handling will be rendered, the router doesn't just render things from the main file it controls the routes and which components to mount in the App component(Usually called an AppController) so you need to build a Home component that will render at the /route and declare that using IndexRoutein your router then set Links between the components and if everything is done properly than you should be good to go.

您的 App 组件不应该真正渲染任何东西,{this.props.children}因为路由器正在处理的所有组件都将在此处渲染,路由器不只是从它控制路由的主文件中渲染内容以及在应用程序中安装哪些组件组件(通常称为 AppController),因此您需要构建一个 Home 组件,该组件将在/路由中呈现并声明IndexRoute在您的路由器中使用,然后在组件之间设置链接,如果一切都正确完成,那么您应该很高兴。

Link:

关联:

<Link to="example">
  Click Me!
</Link>

Main:

主要的:

import React from 'react';
import {ReactDOM, render} from 'react-dom';
import App from './Components/AppComponent';
import Home from './Components/Home';
import Example from './Components/ExampleComponent';
import { Router, Route, IndexRoute, Link, IndexLink, browserHistory } from 'react-router'


ReactDOM.render((
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={Home}>
            <Route path="example" component={Example}/>
        </Route>
    </Router>
), document.getElementById('App'));

AppController:

应用控制器:

import React from 'react';

class App extends React.Component {

  render() {
    return (
      <div>
        <div className="routerView">
          {this.props.children}
        </div>
      </div>
    );
  }
}

export default App;

Example Component:

示例组件:

import React from 'react';
import {Link} from 'react-router';


class Example extends React.Component {
    render(){
        return(
          <div>
              Example
              <Link to="/">Click Me!</Link>
          </div>
        )
    }
}

export default Example

Home component:

主页组件:

import React from 'react';
import {Link} from 'react-router';

class Home extends React.Component {
    render(){
        return (
            <div>
               Home
               <Link to="/example">To Example!</Link>
            </div>
        )
    }
}

export default Home

回答by a_m_dev

as of react router v4, if you are using webpack with react you need to add devServersettings in your webpack.config.jsfile to prevent this issue. just make sure that your devServerconfig has historyApiFallbackset to true, if it is not you will get Cannot get error in browser , i just put a simple devServerconfig from my webpack.config.js file that currently i'm working on , maybe helps someone....

从 react router v4 开始,如果您将 webpack 与 react 一起使用,则需要devServerwebpack.config.js文件中添加设置以防止出现此问题。只需确保您的devServer配置已historyApiFallback设置为true,如果不是,您将在浏览器中收到无法获取错误,我只是devServer从我目前正在处理的 webpack.config.js 文件中放置了一个简单的配置,也许可以帮助某人.. ..

module.exports = {

 ...

 devServer: {
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 3000,
    open: true,
    historyApiFallback: true,
    stats: 'minimal'
  }

 ...

}

回答by myDoggyWritesCode

I got exactly the same problem as the question.

我遇到了与问题完全相同的问题。

After trying the above answer, I am still getting the same error, Interestingly, there is also syntax error in above answer where <IndexRoute component={Home}>must be closed or self closed.

尝试上述答案后,我仍然遇到相同的错误,有趣的是,上述答案中也存在语法错误,<IndexRoute component={Home}>必须关闭或自关闭。

Two ways I could make my thing work:

我可以通过两种方式使我的事情发挥作用:

1)Not a perfect way but other way of making it work is using hashHistoryJust import { Router, Route, IndexRoute, hashHistory } from 'react-router';and modify Router as <Router history={hashHistory}>

1)不是一个完美的方法,但其他使它工作的方法是使用hashHistoryJustimport { Router, Route, IndexRoute, hashHistory } from 'react-router';并将 Router 修改为<Router history={hashHistory}>

Now URL, looks like http://localhost:5000/#/example?_k=a979lt

现在 URL,看起来像http://localhost:5000/#/example?_k=a979lt

2)You can use useHistoryas well.

2)你也可以使用useHistory

But this also adds # in the URL but it looks like http://localhost:5000/#/exampleWhere query parameters aren't present in the link because we'll set them as false..

但这也会在 URL 中添加 # 但它看起来像 http://localhost:5000/#/example链接中不存在查询参数,因为我们将它们设置为 false..

3)In my case, with browserHistory, if I use my Routes as localhost:5000/#/example then it works fine and without hash it doesn't.

3)在我的情况下,browserHistory如果我使用我的路由作为 localhost:5000/#/example 那么它工作正常,没有散列它不会。

Check this link for more details for each of them. https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md

检查此链接以获取每个人的更多详细信息。 https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md

EDIT:Finally, I got my solution to make it work using browserHistory. Please check this out. https://stackoverflow.com/a/38585657/3241111

编辑:最后,我得到了使用 browserHistory 使其工作的解决方案。请检查一下。https://stackoverflow.com/a/38585657/3241111

回答by thierno

Try adding exactbefore the path of the App component

尝试在 App 组件的路径之前添加精确

render((
    <Router history={browserHistory}>
        <Route exact path="/" component={App}>
            <Route path="example" component={Example}/>
        </Route>
    </Router>
), document.getElementById('App'));