Angular 首次站点访问非根路径在本地工作,但在生产中不工作 [英] Angular first site visit non-root path works locally but not in production

查看:19
本文介绍了Angular 首次站点访问非根路径在本地工作,但在生产中不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Angular 4 应用程序中,如果我在第一次访问该站点时在 url 中键入一个非根路径(即 localhost:4200/projects),我的应用程序将被引导并且正确组件在浏览器中被渲染到屏幕上.

In my Angular 4 application, if I type a non-root path into the url as my first visit to the site (i.e. localhost:4200/projects), my application is bootstrapped and the correct component is rendered to the screen in the browser.

但是,一旦我通过 IIS 为站点提供服务,如果我转到 http://<my-domain>.com/projects,我会收到 404 错误(不是来自我的应用程序)并且应用程序永远不会被引导.

However, once I serve the site through IIS, if I go to http://<my-domain>.com/projects, I get a 404 error (not from my application) and the application is never bootstrapped.

如何在第一次访问生产中的站点时访问非根路径,以识别应用程序是 Angular 应用程序并引导应用程序访问任何根路径或更高路径?

How do I get a visit to a non-root path as the first visit to the site in production to recognize that the application is an Angular application and bootstrap the application for any path that is the root or beyond?

推荐答案

查看my answer here以获得更详细的解释为什么会这样.一个简短的片段:

See my answer here for a more detailed explanation of why this is happening. A short snippet:

在应用的部署版本上,托管它的网络服务器知道仅如何提供它看到的一个 html 文件 (index.html),它对应于您的根路径.您尝试直接访问的第二个http://url-to-your-app/art 例如,服务器会抛出一个404未找到,因为它没有将其识别为资源的路径可以服务.

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:

For IIS, the easiest way to fix this is to add this to your 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 进行响应.

What this does is instruct IIS to respond with your index.html whenever a 404 is detected.

另一种方法是设置 URL 重写,但这需要安装和配置重写模块,与上述解决方案相比,我认为这太麻烦了.

Another way would be to setup URL rewriting, but that requires the rewriting module to be installed and configured, and it's just too much of a hassle in my opinion compared to the solution above.

这篇关于Angular 首次站点访问非根路径在本地工作,但在生产中不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆