How to proxy requests in Angular
June 20, 2021
There might be situations when you’d like to proxy the requests your client makes. For example, you might have your client running on http://localhost:8000
and your API on http://localhost:8001
. Whatever the URLs or the reason, if you want to divert calls, Angular allows you to proxy your requests.
Proxying is useful in many situations. One might be that in non-dev environments, your client is deployed on the same server as the API. Therefore, you probably make your service calls to /api
, not to <host>/api
. However, when developing the app on your local machine, Angular starts the server on localhost, where you might not have the API server running. In this scenario, Angular will try to make calls to localhost/api
, reaching nothing. This is where the proxy comes in handy. With it, you will be able to redirect those dead calls to the actual API server.
In our above example, we assume that you started the API server on port 8001
. So now if you want to divert requests to http://localhost:8001
, there are a few simple steps to follow.
- Create a
proxy.config.json
in yoursrc
folder -
In that file, add the following:
{ '/api/*': { target: "http://localhost:8001" secure: false } }
- Append the
--proxy-config proxy.config.json
to yourng serve
command. So it will look like so:ng serve --proxy-config proxy.conf.json
After restarting the application, it will divert all your /api/*
calls to http://localhost:8001/api
.
More information on the possible configurations can be found on webpack documentation page (as that’s what powers Angular proxies).
Written by Alex Tanasie, a passionate web developer from Romania. Find me on LinkedIn.