8

I try to create an angular2 app with NodeJS (Express) as a server. The problem is that there is a conflict as Express tries to use its own template engine, and route the requests, while angular also uses routes and index.html as the entry point.

How can I integrate both?

Yuvals
  • 3,094
  • 5
  • 32
  • 60
  • An angular2 project set up and running, but I am afraid that if I create the Express server it will override the file structure. I couldn't find a decent reference how to solve it – Yuvals Oct 20 '16 at 21:26
  • Does this solve it? http://stackoverflow.com/a/34864585/2112228 – sharko Oct 20 '16 at 21:34

1 Answers1

14

Typically, NodeJS/Express would be used to serve an API with endpoints that Angular can consume. NodeJS would be a backend only, Angular would be a frontend only.

While Angular can be served from a NodeJS server, it's a waste of resources since most Angular sites are totally static. That is, they're javascript, CSS and images that could be served from S3 or an FTP and get all their dynamic content via services (tweets from twitter, images from an S3 bucket, data from your custom NodeJS backend, etc.). In other words, no dynamic server side rendering required.

I would strongly recommend maintaining this approach. Host your Angular app on a static storage host like S3 and create a REST API using NodeJS which your app can talk through via Angular services. Send GET requests to fetch JSON data. Take the resulting JSON data and use it to populate your app. Send POST, PUT and DELETE requests to add or manipulate data (assuming you plan to have a backend database).

The way this is usually represented on your domain would be to have http://yourdomain.com point to your Angular app. Your angular app would then make calls to http://yourdomain.com/api/ or http://api.yourdomain.com which are pointed at your Node API. You can configure your DNS to do either of these without the need for physical subdirectories in your code.

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • But do I have to split their locations? what if I want them to run from the same parent directory/project? – Yuvals Oct 20 '16 at 21:27
  • You can host them on different places but configure your DNS so they host from what appears to be the same domain. I'd strongly advise against trying to mix backend and frontend code in a single codebase. – Soviut Oct 20 '16 at 21:31
  • I've updated the answer to include more info about typical hosting setups. – Soviut Oct 20 '16 at 21:33
  • Thank you for the clear explanation - I am glad I did not run into solving collisions with Angular/Express. In any case is it recommended the servers physically? – Yuvals Oct 20 '16 at 21:37
  • The implementation is up to you but a good solution would be to host your angular app on S3 and your NodeJS API on a service like Heroku. Then just configure your DNS in front of both. – Soviut Oct 20 '16 at 21:50