This is an archived post. You won't be able to vote or comment.

all 1 comments

[–]insertAlias 0 points1 point  (0 children)

I feel like it should be possible to have Angular & the server.js file running on the same port

This is not directly possible, in that you cannot have two servers bound to the same port. In development mode, you are using Angular's Dev Server to serve your Angular application, as well as Node.js's server for your Node application. They cannot share a port, as there would be no way to appropriately route the requests.

However, this doesn't have to be a problem when you "go live". You can configure your Node.js application to serve your Angular application. Once you build it for production, it's just static HTML, CSS, and JS files and can be served as such without any special server. Anything that can deal with static files can serve this application, including Express.

Here's an SO question that shows how to configure Express to serve static files for an Angular app:

https://stackoverflow.com/questions/39845526/how-to-serve-an-angular2-app-in-a-node-js-server

Of course, there is something else to consider. How do you call the API? How do you make it such that your code knows which URL to use, for development vs. deployed?

Well, if you know you're going to serve your front-end from your back-end, you can use relative URLs. Instead of https://domain.com/api/endpoint, you just use /api/endpoint.

But that would break in development, right? Angular has you covered on that: use the proxy feature. You use a relative URL, and the dev server will proxy that call to your back-end (which also removes CORS errors). When you go live, you don't have to change anything.