Angular 首次站点访问非根路径在本地有效但在生产中无效
Angular first site visit non-root path works locally but not in production
在我的 Angular 4 应用程序中,如果我在 url 中键入非根路径作为我第一次访问该站点(即 localhost:4200/projects
),我的应用程序是 bootstrapped 并在浏览器中将正确的组件呈现到屏幕上。
但是,一旦我通过 IIS 为站点提供服务,如果我转到 http://<my-domain>.com/projects
,我会收到 404 错误(不是来自我的应用程序)并且该应用程序永远不会 bootstrapped。
如何在首次访问生产站点时访问非根路径,以识别该应用程序是 Angular 应用程序并且 bootstrap 任何路径的应用程序那是根还是根?
请参阅 以更详细地解释为什么会发生这种情况。
一小段:
On the deployed version of your app, the web server hosting it knows
only how to serve the one html file it sees (index.html), which
corresponds to your root path. The second you try to access directly
http://url-to-your-app/art for example, the server will throw a 404
not found, as it does not recognize that as the path of a resource it
can serve.
对于 IIS,解决此问题的最简单方法是将其添加到您的 web.config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpErrors>
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/index.html" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
</configuration>
这样做是指示 IIS 在检测到 404 时用您的 index.html 进行响应。
另一种方法是设置URL重写,但这需要安装和配置重写模块,与上面的解决方案相比,我认为这太麻烦了。
在我的 Angular 4 应用程序中,如果我在 url 中键入非根路径作为我第一次访问该站点(即 localhost:4200/projects
),我的应用程序是 bootstrapped 并在浏览器中将正确的组件呈现到屏幕上。
但是,一旦我通过 IIS 为站点提供服务,如果我转到 http://<my-domain>.com/projects
,我会收到 404 错误(不是来自我的应用程序)并且该应用程序永远不会 bootstrapped。
如何在首次访问生产站点时访问非根路径,以识别该应用程序是 Angular 应用程序并且 bootstrap 任何路径的应用程序那是根还是根?
请参阅
On the deployed version of your app, the web server hosting it knows only how to serve the one html file it sees (index.html), which corresponds to your root path. The second you try to access directly http://url-to-your-app/art for example, the server will throw a 404 not found, as it does not recognize that as the path of a resource it can serve.
对于 IIS,解决此问题的最简单方法是将其添加到您的 web.config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpErrors>
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/index.html" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
</configuration>
这样做是指示 IIS 在检测到 404 时用您的 index.html 进行响应。
另一种方法是设置URL重写,但这需要安装和配置重写模块,与上面的解决方案相比,我认为这太麻烦了。