Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

routing - Angular first site visit non-root path works locally but not in production

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.

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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>

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...