反应路由器弄乱了请求网址
React-router messes up request urls
我正在尝试使用 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
在组件中直接调用它。
- 反应路由器弄乱了请求网址
- PHP 代码中的 CSS 弄乱了 IE9 中的布局
- Node/Angular中的$http GET请求收到了奇怪的响应
- 什么'这个AJAX请求错了
- 为什么我的冰候选请求触发了 6 次而不是 1 次
- 动画不透明度弄乱了我的文本
- 滚动弄乱了我的画布鼠标坐标 - Javascript Telerik Mobile
- jQuery加载弄乱了布局
- Sencha Touch Ajax 请求调用了两次
- jQuery弄乱了DIV的z索引
- Ajax 请求减慢了函数的其余部分,如何修复
- 谷歌浏览器扩展弄乱了正则表达式全局标志
- JS触发的文件下载弄乱了重音字符
- 为什么Google.com's的源代码太乱了
- Marketo-Munchkin同步请求损害了JS的性能
- 多个ajax请求过了一段时间不起作用
- 添加倒计时,使用jquery.弄乱了页面.我做错了什么?
- 为什么io请求发送了那么多次
- IE9+弄乱了我的JSON对象
- 模态中的链接在打开模态之前出现,弄乱了页面界面