Hey guys 👋👋, in this article, I will be describing how to serve a VueJs client-side application from DotNet.
Some of the benefits of serving a VueJs App from DotNet are that you get to enjoy the speed and performance of DotNet and you could also setup API routes from the same DotNet server which gives you the benefit of not writing extra code for CORS (Cross-Origin Resource Sharing ) since both the web app and API are from the same origin( eg https://myvueapp.com and https://myvueapp.com/api/users ).
So below are screen shots of the simple VueJs application I made. It only has two routes ( “/” and “/about”).
In the image above the RouterView component in the App.vue template renders the Home.vue template when the route is at the root(“/”) and renders the About.vue template when the route is “/about”.
Below is the simple DotNet server code that serves the static resources.
With this setup above you would encounter 404(Not found) errors because the root(“/”) and “/about” route are only available on the client with the aid of the History API but not available on the server.
Running the server above introduced the errors in the image below:
Navigating to “http://localhost:5195/index.html” route worked 😅
The problem with the page above is that it doesn’t render the Home.vue template and neither would it render the About.vue template and this is because the routes that can render a template is the root(“/”) or the “/about” route. So therefore “/index.html” won’t work.
To resolve this issue I had to use a middleware that returns the index.html file when the request sent from the browser has a route without a file extension (eg “/” and “/about” and not “file.js” or “.css”). So that means when I navigate to either the root(“/”) or the “/about” route the index.html file in my “/client/dist” folder would be sent to the browser while the history API does its work of rendering the proper template.
The files “/client/dist” folder contains the built Vue.js app which got generated by executing the npm run build command.
The code below solves the problem.
Executing the code above enables correct rendering of templates on the browser 😎
The simple VueJs application works properly and now I get to enjoy the benefits of DotNet 🥂🍾. For access to the code you can click here
Hope you learnt something new 😎.