Home > OS >  How do Node.js and Angular connect together?
How do Node.js and Angular connect together?

Time:05-02

I manage to create Angular apps in general, but I do not understand how Angular and Node.js connect together.

Even on a local environment, you need to launch two things:

  • ng serve
  • node app.js

So how the two connect? Do you render the Angular app via Node.js? Do you render the app like this:

img1

or like this:

img2

But then there is the route problem, do you define routes via Node.js with app.get('/') or via Angular with:

const routes: Routes = [
  { path: '', component: HomeComponent}
];

CodePudding user response:

ng serve & node app.js will launch those two scripts at the same time.

CodePudding user response:

Angular and NodeJS application connect over HTTP where NodeJS is the backend and the Angular is the frontend.

ng serve is the command to server Angular application on your local environment but when you'll deploy your Angular app in production, first you'll have to build the Angular app and serve the destination folder using Nginx or something else..

node app.js is the command you are using to launch your NodeJS server (in your case) which will start listen on some HTTP port (if you are using NodeJS Express correctly)

An example of connection between the two over HTTP is like this: the Angular app issue an HTTP request to the NodeJS backend and the NodeJS server respond to that HTTP request to send data back to the Angular app.

regarding the routing, Angular is a Single Page Application (SPA) so it can handle it own routing requests as you showed and this is what you should use for your website (the frontend) most of the times. where the routes in your NodeJS application refer to your REST API routes, as in what functions your NodeJS server supports.

I think you should read on how to implement REST api in NodeJS and you'll find great detailed guides about it, and creating a single page application in Angular

  • Related