我正在使用React-router,当我点击链接按钮时,它工作得很好,但当我刷新我的网页时,它没有加载我想要的东西。

例如,我在localhost/joblist和一切都很好,因为我到达这里按下一个链接。但如果我刷新网页,我会得到:

Cannot GET /joblist

默认情况下,它不是这样工作的。最初我有我的URL localhost/#/和localhost/#/joblist,他们工作得很好。但我不喜欢这种类型的URL,所以试图删除#,我写道:

Router.run(routes, Router.HistoryLocation, function (Handler) {
 React.render(<Handler/>, document.body);
});

这个问题不会发生在localhost/,这个总是返回我想要的。

这个应用程序是单页的,所以/joblist不需要向任何服务器询问任何事情。

我的整个路由器。

var routes = (
    <Route name="app" path="/" handler={App}>
        <Route name="joblist" path="/joblist" handler={JobList}/>
        <DefaultRoute handler={Dashboard}/>
        <NotFoundRoute handler={NotFound}/>
    </Route>
);

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

当前回答

前面的答案并不能解决您想要使用代理通道的浏览器路由器,而又不能使用root的问题。

对我来说,解决办法很简单。

假设您有一个指向某个端口的URL。

location / {
  proxy_pass http://127.0.0.1:30002/;
  proxy_set_header    Host            $host;
  port_in_redirect    off;
}

现在由于浏览器路由器,子路径被破坏了。但是,你知道子路径是什么。

这个问题的解决方案是什么?对于子路径/联系人

# Just copy paste.
location /contact/ {
  proxy_pass http://127.0.0.1:30002/;
  proxy_set_header    Host            $host;
}

我试过的其他方法都不管用,但这个简单的方法奏效了。

其他回答

如果你在IIS上托管React应用程序,只需添加一个web。配置文件包含:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <httpErrors errorMode="Custom" existingResponse="Replace">
            <remove statusCode="404" subStatusCode="-1" />
            <error statusCode="404" path="/" responseMode="ExecuteURL" />
        </httpErrors>
    </system.webServer>
</configuration>

这将告诉IIS服务器将主页返回给客户端,而不是404错误,并且不需要使用哈希历史。

我用React路由器(Apache)为我的SPA找到了解决方案。只要在文件.htaccess中添加这个:

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

来源:Apache的React路由器配置

如果您在谷歌桶上运行它,简单的解决方案是考虑'index.html'为错误(404 not found)页面。

这样做:

在桶的列表中,找到您创建的桶。 单击桶关联的桶溢出菜单(…),选择“编辑网站配置”。 在网站配置对话框中,将主页也指定为错误页面。

当我在Electron中使用React作为前端,使用React -router-dom作为路由时,我就遇到了这个问题。

我用HashRouter替换了BrowserRouter,这是固定的。

这里有一个简单的例子:

import {
  HashRouter as Router,
  Switch,
  Route,
} from "react-router-dom";

产品堆栈:React, React Router v4, BrowswerRouter, Express.js, Nginx

User BrowserRouter for pretty URLs File app.js import { BrowserRouter as Router } from 'react-router-dom' const App = () { render() { return ( <Router> // Your routes here </Router> ) } } Add index.html to all unknown requests by using /* File server.js app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) { if (err) { res.status(500).send(err) } }) }) bundle Webpack with webpack -p run nodemon server.js or node server.js

你可能想让nginx在服务器块中处理这个问题,忽略第2步:

location / {
    try_files $uri /index.html;
}