Yuvals Yuvals - 1 month ago 12
Node.js Question

How to integrate ExpressJS server with Angular2

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?

Answer

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.

Comments