I have an AngularJS SPA application that I have developed using Visual Studio 2015. When I click publish it publishes the index.html and works just fine. However if I am on a page and I click refresh then it tries to do a refresh of the SPA page such as example.com/home/about. This fails as I don't have a home/about page.
Is there some way that I could modify my web.config file (just for local testing) so that it would actually go to the index.html (load that up) and then to the /home/about state?
Here's my current web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
It seems you are using html5mode. In this case there's no #
to keep the URL changing from requesting to the server.
With this configuration, you need help from the server. It will serve the index.html when it receives requests from your SPA routes.
This SO answer has details on configuring URL Rewrite on web.config:
Rules go by:
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS 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="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
It assumes your API is under: /api
and for any directory or file that it finds, it serves as-is.
Anything else, gets rewritten to /
which having default document configured to index.html
, will load you SPA.
Also note you need to install the URL Rewrite module for IIS (IIS Express doesn't need the module)
Another option is one of these lightweight HTTP servers npm packages. John Papa has one: lite-server. It uses BrowserSync under the hood:
BrowserSync does most of what we want in a super fast lightweight development server. It serves the static content, detects changes, refreshes the browser, and offers many customizations.
When creating a SPA there are routes that are only known to the browser. For example, /customer/21 may be a client side route for an Angular app. If this route is entered manually or linked to directly as the entry point of the Angular app (aka a deep link) the static server will receive the request, because Angular is not loaded yet. The server will not find a match for the route and thus return a 404. The desired behavior in this case is to return the index.html (or whatever starting page of the app we have defined). BrowserSync does not automatically allow for a fallback page. But it does allow for custom middleware. This is where lite-server steps in.
lite-server is a simple customized wrapper around BrowserSync to make it easy to serve SPAs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With