Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Node Express server and Angular on the same port?

I am new to Node and Angular. I need to know whether is it possible to run a Node Express app serving as a backend and an Angular frontend on the same port. I followed Angular Quickstart tips on angular.io and created a Node todo application but both are running on different port which raises the issue of Cross Origin Request Blocked Issue.

like image 497
Swapnil Deo Avatar asked Jun 03 '17 14:06

Swapnil Deo


People also ask

How do I use node and Angular together?

One way to build Angular application is with NodeJS or Java, and the other method is in which we first build Angular, serve the static content with NGINX. If we are using it with NodeJS, then we also need to deal with server code. For example, the index. html page must be loaded with node.

Can Express and react on same port?

Neither react nor node use any network ports as they have no networking capabilities themselfs. It's the web server (e.g. express js) which uses node as the runtime environment or the database server that use ports. You can serve your assets (react app, html, css) from the same web server.

What port to run Express on?

js with express is accessible only via port 80.


1 Answers

To have Node.js serve the Angular app on the same port, your Angular app must be deployed under your Node's directory where the static resources are deployed. But in dev mode, it's more productive to serve your Angular bundles (so they auto-rebuild in memory as you code) from the dev server, e.g. on port 4200, while the Node server runs on another port, e.g. 8080.

To avoid cross-origin issues, you need to configure a simple proxy file in your Angular app to redirect all data requests to your Node server. For example, create a file proxy-conf.json in the root dir of your Angular project:

{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

This will redirect all requests that have /api in the URL to your Node server, assuming that it runs on port 8080. Then start your Angular app using the following command:

ng serve --proxy-config proxy-conf.json

An HTTP request in your Angular App can look like this:

http.get('/api/products');

Of course, you need to configure the /api/products endpoint for GET requests on your Node server.

like image 73
Yakov Fain Avatar answered Sep 28 '22 17:09

Yakov Fain