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

I am new to Node and Angular. I need to know if it is possible to run a Node Express application acting as a backend and Angular interface on the same port. I followed the Angular Quickstart prompts on Angular.io and created the todo Node application, but both work on a different port, which causes the Cross Origin Request block request.

+12
source share
3 answers

To get Angular and Express on the same port, I always worked with my Angular build files using the Express application itself. You should be able to tell Express to serve static content from the Angular build directory as follows:

app.use(express.static('../accounting-client/dist')); 

That would work if you had such a file structure and serve.js was serve.js with Node:

 -accounting-server -serve.js -accounting-client -dist/* 

You can customize it as needed by setting up the Angular build folder so that it is where you need it, or use Grunt / Gulp to move files to the folders you prefer with the build task.

As Jacob mentioned, this is not an ideal development solution, as it will not work with automatic updating of the Angular server.

+9
source

In order for Node.js to serve an Angular application on the same port, your Angular application must be deployed to the Node directory where the static resources are deployed. But in dev mode, it is more productive to serve your Angular packages (so that they automatically rebuild in memory during encoding) from the dev server, for example, through port 4200, while the Node server runs on a different port, for example, 8080.

To avoid problems with multiple sources, you need to configure a simple proxy file in your Angular application to redirect all data requests to your Node server. For example, create a proxy-conf.json file in the root directory of your Angular project:

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

This will redirect all requests with /api in the URL to your Node server, provided that it runs on port 8080. Then launch the Angular application using the following command:

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

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

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

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

+10
source

The fact that you need to have access to your project on the client side from an Express project, as spacefozzy pointed out , is true. but you can still split your projects.
To do this, you can create a symbolic link from your client-side project directory in the Express project directory:

 // while in Express directory ln -s ~/path/tp/client-side/build name-in-espress-dir 

This way you can isolate projects.

0
source

Source: https://habr.com/ru/post/1268504/


All Articles