After I deployed a SPA Application in history mode to my linux azure app service, I found out that my routing was not working correctly.
What is history mode?
The default mode for
vue-router
is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes.When using history mode, the URL will look “normal,” e.g.
http://oursite.com/user/id
. Beautiful!Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access
http://oursite.com/user/id
directly in their browser. Now that's ugly.
Server configuration they say, hmm I don’t like that, So I found a neat way to fix it on the application level.
Fixing the routing
Inside your statup.cs you’ll most likely use the “useMvc” method. Inside this method simply add the following:
routes.MapRoute("spa-routes", "{*anything}", new { controller = "Home", action = "Index" });
/{*anything}
-> if a file exists there, return it as static content; otherwise if SPA can route it, have SPA route it; otherwise return default route inside the SPA.
Another way of achieving the same result can be done with:
routes.MapSpaFallbackRoute("spa-routes", new { controller = "Home", action = "Index" });
If you have your api in the same project, you can add a wildcard for the api map route aswell.
Simple as that!
Happy coding! :)