【发布时间】: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