我正在使用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);
});
如果试图从IIS虚拟目录(不是网站的根目录)服务React应用程序:
在设置重定向时,'/'不会单独工作。对我来说,它也需要虚拟目录名。下面是我的网页配置:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<defaultDocument>
<files>
<remove value="default.aspx" />
<remove value="iisstart.htm" />
<remove value="index.htm" />
<remove value="Default.asp" />
<remove value="Default.htm" />
</files>
</defaultDocument>
<rewrite>
<rules>
<rule name="React Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/YOURVIRTUALDIRECTORYNAME/" />
</rule>
</rules>
</rewrite>
<directoryBrowse enabled="false" />
<httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
<remove statusCode="500" subStatusCode="100" />
<remove statusCode="500" subStatusCode="-1" />
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="403" subStatusCode="18" />
<error statusCode="403" subStatusCode="18" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
<error statusCode="404" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
<error statusCode="500" prefixLanguageFilePath="" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
<error statusCode="500" subStatusCode="100" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
</configuration>
除了网络。配置文件,React应用程序本身需要一些改变:
在文件包中。Json,你需要添加一个'主页'条目:
{
"name": "sicon.react.crm",
"version": "0.1.0",
"private": true,
"homepage": "/YOURVIRTUALDIRECTORYNAME/",
"dependencies": {
...
我将basename添加到我的浏览器历史对象中,并将其传递给路由器以访问历史:
import {createBrowserHistory } from 'history';
export default createBrowserHistory({
//Pass the public URL as the base name for the router basename: process.env.PUBLIC_URL
});
我还在我的React路由器文件App.js中添加了这个属性:
<Router history={history} basename={process.env.PUBLIC_URL}>
最后,在index.html文件中,我在'title'标签上方添加了以下选项卡:
<base href="%PUBLIC_URL%/">
也许有些步骤是不需要的,但这似乎已经完成了我的工作。我不知道如何设置它运行在一个站点的根目录或虚拟目录,而不需要重新编译,作为包中的主页。据我所知,json不能在构建后交换。
为乔舒亚·戴克的答案添加更多信息。
如果你正在使用Firebase,并且想同时使用根路由和子目录路由,你需要在你的Firebase .json中添加以下代码:
{
"hosting": {
"rewrites": [
{
"source": "*",
"destination": "/index.html"
},
{
"source": "/subdirectory/**",
"destination": "/subdirectory/index.html"
}
]
}
}
例子:
你正在为客户建立一个网站。您希望网站的所有者在https://your.domain.com/management中添加信息,而网站的用户将导航到https://your.domain.com。
在这种情况下,您的火源。Json文件是这样的:
{
"hosting": {
"rewrites": [
{
"source": "*",
"destination": "/index.html"
},
{
"source": "/management/**",
"destination": "/management/index.html"
}
]
}
}
我刚刚用Create React App做了一个网站,也遇到了同样的问题。
我使用react-router-dom包中的BrowserRouting。我在Nginx服务器上运行,添加以下到/etc/nginx/yourconfig.conf为我解决了这个问题:
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.html break;
}
}
如果你正在运行Apache,这对应于在.htaccess中添加以下内容:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
这似乎也是Facebook自己提出的解决方案。
如果您正在使用“create-react-app”命令,
生成一个React应用程序,然后生成包。json文件需要有一个更改,以在浏览器中正常运行的产品构建React SPA。打开文件包。Json,并添加以下代码段,
"start": "webpack-dev-server --inline --content-base . --history-api-fallback"
这里最重要的部分是“——history- API -fallback”,用于启用历史API回调。
如果使用Spring或任何其他后端API,有时会出现404错误。因此,在这种情况下,您需要在后端有一个控制器,将任何请求(您想要的)转发给index.html文件,由react-router处理。下面演示了一个使用Spring编写的示例控制器。
@Controller
public class ForwardingController {
@RequestMapping("/<any end point name>/{path:[^\\.]+}/**")
public String forward(HttpServletRequest httpServletRequest) {
return "forward:/";
}
}
例如,如果我们取一个后端API REST端点为“abc”(http://localhost:8080/abc/**),任何到达该端点的请求都将重定向到React应用程序(index.html文件),然后React -router将处理它。