反应路由器混淆请求url
我正在试图通过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'))
将请求发送到预期的URL http:localhost:3001/api/threads
并返回数据,并且一切正常。
作为一个侧面说明,我有端口3000设置为webpack热负载前端和端口3001设置为Express后端。
在快递方面,我有以下路线设置:
router.get('/api/threads', function (req, res, next) { Thread.find(function (err, threads) { if (err) { return next(err); } res.json(threads) }) })
访问本地主机:3001 / API /线程返回预期的数据。 localhost:3001返回Cannot GET '/'
预期的Cannot GET '/'
。
首先,如果一个URL用作API端点,而不是直接在浏览器中,那么它可能根本不属于你的react-router。 只将path放在您期望在浏览器中呈现视图的路由器中 。 所以如果你想让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端点,您可以通过它的完整path( localhost:3001/api/threads
) 在组件directl中调用它 。