【问题标题】:React-router messes up request urlsReact-router 弄乱了请求的 url
【发布时间】:2016-09-13 20:55:34
【问题描述】:

我正在尝试使用 react-router 实现以下嵌套 url。我的问题是,当嵌套在路由器组件中时,Feed 组件将 GET 和 POST 请求发送到错误的 url,如下所示:

ReactDOM.render((
                <Router history = { browserHistory }>
                  <Route component={ NavBar }>
                    <Route path='/' component={ Feed } url='/api/threads' pollInterval={ 2000 } />
                    <Route path='signup' component={ Signup } />
                  </Route>
                </Router>
  ), document.getElementById('root'));

http://localhost:3000/?_=1463499798727 发送请求,返回index.html 的内容,这会导致错误,因为ajax 请求需要json 数据,而不是html,并且无论如何都是错误的。

同时

ReactDOM.render((
                <Router history = { browserHistory }>
                  <Route component={ NavBar }>

                    <Route path='signup' component={ Signup } />
                  </Route>
                </Router>
  ), document.getElementById('root'));

ReactDOM.render(<Feed url='/api/threads' pollInterval={ 2000 }/>, document.getElementById('feed'))

向期望的urlhttp:localhost:3001/api/threads发送请求并返回数据,一切正常。

附带说明一下,我为 webpack-hot-load 前端设置了 3000 端口,为 Express 后端设置了 3001 端口。

在 Express 方面,我设置了以下路线:

  router.get('/api/threads', function (req, res, next) {
    Thread.find(function (err, threads) {
      if (err) { return next(err); }
      res.json(threads)
    })
  })

访问 localhost:3001/api/threads 会返回预期的数据。 localhost:3001 返回 Cannot GET '/' 这是预期的。

【问题讨论】:

  • “向预期的 URL 发送请求”是什么意思?
  • @mtaube:在第一个示例代码中,react 应用程序不断尝试从localhost:3000/?_=1463499798727 获取数据,这会导致错误。在第二个示例中,react 应用 GET 请求 http:localhost:3001/api/threads,它连接到 express 中的 API 端点
  • 您是说您正在尝试使用localhost:3001/api/threads 作为API 端点吗?如果是这样,它根本不属于您的路由器。
  • 是的,我是。奇怪的是,在正常渲染组件但不在路由器内部时,将 url 作为道具传递是有效的
  • 或者您是说您想将localhost:3001/api/threads 用作 API 端点(返回 JSON)和前端浏览器 URL(返回 index.html)?

标签: javascript node.js reactjs react-router


【解决方案1】:

首先,如果一个 URL 旨在用作 API 端点而不是直接在浏览器中,那么它可能根本不属于您的 react-router。 只在路由器中放置您希望在浏览器中呈现视图的路径。因此,如果您希望 localhost:3001/api/threads 通过 API 调用返回 JSON,请将其从路由器中取出。

此外,您应该使用IndexRoute 组织您的路线。试试这个:

<Router history={browserHistory}>
  <Route path="/" component={CoreLayout}>
    <IndexRoute component={Feed} />

    <Route path="signup" component={Signup} />

    <Route path="*" component={NotFoundView} />
  </Route>
</Router>

CoreLayout simple 在哪里渲染它的孩子。我不确定您要为根 URL (localhost:3001) 显示的确切内容,但您可以使用上述组件。

要使用您的 API 端点,您可以直接在组件中调用它y,通过它的完整路径 (localhost:3001/api/threads)。

【讨论】:

  • 我试过了,但不幸的是错误仍然存​​在。我 99% 确定错误不在 Express 端。我花了大约 2 个小时来调试这个,我很确定这是问题所在。
  • 实现这个路由器后,访问localhost:3001会发生什么?您是否尝试使用 localhost:3001/api/threads 作为实际 URL?准确指定您希望使用的 URL。
  • 感谢您的回答,对组件中的 url 进行硬编码有效。但是,我们应该如何将其他 props 传递给组件?
猜你喜欢
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 2018-09-26
  • 2017-01-16
  • 2013-04-05
  • 2020-01-16
相关资源
最近更新 更多