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

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


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.


To get Angular and Express running on the same port I've always served my Angular build files by the Express app itself. You should be able to tell Express to serve static content from an Angular build directory like this:

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

Which would work if you had a file structure like so and were running serve.js with Node:

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

You can customize as needed by configuring the Angular build folder to be wherever you need it, or use Grunt/Gulp to move files around to the folders you prefer with a build task.

As mentioned by Yakov this isn't ideal for development since it won't work with the Angular dev server's auto-refresh.


The fact that you need to have access to your client-side project from within Express project, as spacefozzy said, is true. but you still can keep your projects separated.
To do so, you can create a symlink from your client-side project directory in your Express project directory:

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

This way you can maintain projects isolated.