Your request to /hello
means an absolute path inside the application running the angular application, so the request goes to http://localhost:4200/hello
. Your angular application just doesn't know about the express application you want to target.
absolute urls
If you want to access the hello
route on the other (express) application, you need to explicitly specify this by referencing http://localhost:8080/hello
.
cors
Doing it this way, the correct application is targeted, but you will likely run into CORS issues, because the browser will prevent the javascript code obtained from localhost:4200
to access a server at localhost:8080
. This is a security feature of your browser. So if you want to allow the code at 4200 to access the backend at 8080 your backend can whitelist this so called origin. For details see http://enable-cors.org/ and a corresponding express middleware you could use to support cors in your backend (https://www.npmjs.com/package/cors).
Using this approach has two downsides in my opinion. First, you need a way to tell your frontend under which absolute url it can reach the backend. This must be configurable because you need different urls for dev, staging and production. You then also need a way to manage all your whitelisted urls because the frontend in production will have a different url than when running the frontend in development. This can get pretty cumbersome to handle.
proxying your backend
A better approach in my opinion is to handle this in your infrastructure by proxying
the backend in your frontend application. With proxying you basically tell your frontend server that all requests to some url should be passed through to another application. In your case this could probably mean, that for example you configure a proxy for the path /api/
to proxy the application on localhost:8080
. The server then doesn't try to find a url like /api/hello
on your frontend application but forwards your request to localhost:8080/hello
. In your angular application you then don't need to care about the url of your backend and you can then always do a request to a url like /api/some-express-route
.
For this to work you need to configure your angular dev server to proxy the requests. For details on how to do this, please see the docs at https://angular.io/guide/build#proxying-to-a-backend-server. When going to production, you can do this by configuring your web server, e.g. nginx to proxy the requests.