Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 467
Yuvals Avatar asked Oct 20 '16 21:10

Yuvals


People also ask

Can we use ExpressJS in angular?

It can be installed either locally in a project or globally. The above line will install the express (js) module in the current project. Use the -g (-global) flag to install the module globally. Create a server.

Is ExpressJS cross platform?

js) is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript.


1 Answers

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.

like image 81
Soviut Avatar answered Oct 25 '22 21:10

Soviut