Angular Framework
Imal Perera  

Setup Reverse Proxy for API Endpoints in Angular

Spread the love

Angular is all about single page applications, which means you often needs to communicate with a remote REST server. Now the problem is your development environment is running in localhost and the API is hosted in a remote server so you get problems with same origin policy, even though you get this fixed by adding  little server tweaks next problem you are facing is mimicking production environment in your local server. If I explain the second fact little more, you want to have the production environment and the local environment similar so that without any changes your integration servers can pull the code and deploy the the production environment.

for example in your production environment

www.abc.com  ==> will respond you with your angular app code

but

www.abc.com/api ==> will be having a reverse proxy configured so that any requests to this will be handled in REST server

now in your angular application your service calls should be point to www.abc.com/api 

This means in your local setup also should be configured in a way that localhost:port  should come up with the angular project and anything localhost:port/api should direct to remote REST server inorder to keep the environments similar so that you do not want to do any changes when the code is deployed to the production server.

To achieve this task you need to setup a reverse proxy in your npm server, to do that

  1. edit "start" of your package.json to look below
    "start": "ng serve --proxy-config proxy.conf.json",
  2. create a new file called "proxy.conf.json" in the root of the project and inside of that define your proxies like below

    { "/api": {
          "target": "http://api.yourdomai.com",
          "secure": false
       }
    }
    

  3. Importnat thing is that you use npm start instead of ng serve

Read more from here : Proxy Setup angular 2 cli

Here is my stackoverflow answer : Reverse Proxy Angular

Leave A Comment