I recently made some simple single page applications using AngularJS but I never used a server, I rant it locally... Today I started with a NodeJS course and there was something bothering me... For example, if I have a request on 127.0.0.1:1330 and there is an NodeJS server listening on this address/port, I have to choose which data I will respond, according to the URL ( for example: i will respond with index.html if the URL is '/' ). Moving forward... Assuming that this page uses an external script resource, then I have to configure a route to respond with the script file when it is requested, and here is where my doubt comes in... If you have an AngularJS application, the concept of the whole thing is to load all the HTML/Script files in the start, so you won't have to make a new request when you change the URL ( using HREF in Angular to fake URLS ) and the the whole thing is broken if you need the NodeJS server to respond with the correct file each time the URL changes. I think I'm make some confusion with NodeJS routing and AngularJS routing.
-
For SPA the server should respond with static file if it exists and with index.html otherwise. If by 'NodeJS' server you mean Express, you may check any Express+Angular starter for example.Estus Flask– Estus Flask2016-11-07 00:31:07 +00:00Commented Nov 7, 2016 at 0:31
-
@estus This will help me a lot. I am really new to web development, and I am looking for a way to put it all together( Angular, Node, Express... ), and I'm not very familiar with the toolks that are at my disposaljulianomontini– julianomontini2016-11-07 00:59:19 +00:00Commented Nov 7, 2016 at 0:59
1 Answer
Usually you'll serve up just the one html page (and it's resources) and rewrite all relevant URLs so they load the same page (assuming router is in html5 mode for pretty urls). If you're not using the html5 mode then angular routes just use the anchor so it has no bearing on the URL as all the server will see is requests to index.html
Non-pretty route (no rewriting required as it just uses anchor)
http://localhost/index.html/#!/myRoute
Pretty route: (server must still serve index.html)
When using pretty URLs angular uses the HTML5 history API to alter the URL displayed in browser - the problem with this is that if the user either navigates to that page directly or if the user refreshes the page the server needs to know that it should send index.html for /myRoute
What you'll load from different urls for a single page app is your data - you might do an AJAX request to contact an endpoint that gets/sets/updates/deletes data.
For further reading the following question has quite a few good answers regarding Angular routing AngularJS routing without the hash in html5 mode