反应路由器弄乱了请求网址

React-router messes up request urls

本文关键字:请求 乱了 路由器弄      更新时间:2023-09-26

我正在尝试使用 react-router 实现以下嵌套网址。我的问题是,当嵌套在路由器组件中时,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'));

将请求发送到返回index.html内容http://localhost:3000/?_=1463499798727,这会导致错误,因为 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'))

将请求发送到预期的 URL http:localhost:3001/api/threads并返回数据,一切正常。

作为旁注,我为 webpack-hot-load 前端设置了端口 3000,为 Express 后端设置了端口 3001。

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

  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 返回预期数据。本地主机:3001 返回预期的Cannot GET '/'

首先,如果一个 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简单渲染的地方是孩子。我不确定您要为根 URL ( localhost:3001 ( 显示什么,但您会使用像上面这样的组件。

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