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.
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.
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.
js with express is accessible only via port 80.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With