繁体   English   中英

刷新页面在react-router 2中给出了不能GET / page_url

[英]Refreshing page gives Cannot GET /page_url in react-router 2

我使用客户端渲染反应0.14和react-router 2.我已将我的应用程序部署到本地节点服务器。

我在url (server_url/component1) 当我刷新页面时,我得到了

Cannot GET /component1 

服务器端的错误。

我知道这种情况正在发生,因为我再次向/component1 server1发送请求服务器,该服务器上不存在该路由。 但是我想在每次刷新页面时禁用它,它应该仅由客户端路由处理。 我不想向服务器发送任何请求。

我的应用程序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');
});

UPDATE

为了让其他路线工作,你应该将它们放在捕捉路线的前面,因为快速应用它们反之亦然(第一个定义的路线将作为最后一个应用):

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 ,但是在任何其他请求中,路由将被传递给你的前端。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM