刷新页面给出 Cannot GET /page_url in react-router 2
Refreshing page gives Cannot GET /page_url in react-router 2
我正在使用带有 React 0.14 和 React-router 2 的客户端渲染。我已经将我的应用程序部署到本地节点服务器。
我在 url (server_url/component1)
。当我刷新页面时,我得到
Cannot GET /component1
来自服务器端的错误。
我知道发生这种情况是因为我再次向服务器发送请求 /component1
服务器上不存在该路由。但是我想在刷新页面时禁用它,它应该只由客户端路由处理。我不想向服务器发送任何请求。
我的应用程序的入口点index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Router,browserHistory} from 'react-router';
import routes from './routes';
ReactDOM.render(
<Router routes={routes} history={browserHistory}/>
, document.querySelector('.init')
);
我的routes.js文件
module.exports = (
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/component1" component={comp1}/>
</Route>
)
编辑:
在这种情况下,我应该使用浏览器历史记录还是哈希历史记录?它们相同吗?
如果我理解正确,那么您必须将所有与定义的路由不匹配的请求重定向到 前端 。如果它只是一个静态 html 文件,路由应该如下所示:
app.get('*', function(req, res) {
res.sendFile('public/index.html');
});
更新
为了让其他路由工作,你应该把它们放在 catching 路由的前面,因为 express 应用它们,反之亦然(第一个定义的路由将被应用为最后一个):
app.get('/any_route_here', (req, res) => {
res.json({msg: 'ROUTE WORKS'})
});
app.get('*', (req, res) => {
res.sendFile('public/index.html'); //pas routing to react
});
以这种方式,如果您发出如下请求:yourserver.host/any_route_here
您将收到 json 消息 ROUTE WORKS,但对于任何其他请求,路由将传递给您的前端。
我正在使用带有 React 0.14 和 React-router 2 的客户端渲染。我已经将我的应用程序部署到本地节点服务器。
我在 url (server_url/component1)
。当我刷新页面时,我得到
Cannot GET /component1
来自服务器端的错误。
我知道发生这种情况是因为我再次向服务器发送请求 /component1
服务器上不存在该路由。但是我想在刷新页面时禁用它,它应该只由客户端路由处理。我不想向服务器发送任何请求。
我的应用程序的入口点index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Router,browserHistory} from 'react-router';
import routes from './routes';
ReactDOM.render(
<Router routes={routes} history={browserHistory}/>
, document.querySelector('.init')
);
我的routes.js文件
module.exports = (
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/component1" component={comp1}/>
</Route>
)
编辑: 在这种情况下,我应该使用浏览器历史记录还是哈希历史记录?它们相同吗?
如果我理解正确,那么您必须将所有与定义的路由不匹配的请求重定向到 前端 。如果它只是一个静态 html 文件,路由应该如下所示:
app.get('*', function(req, res) {
res.sendFile('public/index.html');
});
更新
为了让其他路由工作,你应该把它们放在 catching 路由的前面,因为 express 应用它们,反之亦然(第一个定义的路由将被应用为最后一个):
app.get('/any_route_here', (req, res) => {
res.json({msg: 'ROUTE WORKS'})
});
app.get('*', (req, res) => {
res.sendFile('public/index.html'); //pas routing to react
});
以这种方式,如果您发出如下请求:yourserver.host/any_route_here
您将收到 json 消息 ROUTE WORKS,但对于任何其他请求,路由将传递给您的前端。