How to setup reverse proxy in angular 2

Viewed 5640

package.json file:

"start": "gulp serve.dev --color",

service class:

this.mapUrl = @apiproxy
return this.http.post(this.mapUrl, body, { headers: this.headers })

Proxy.config.json:

{
"/@apiproxy/*": {
"target": "http://url:8080",
"secure": false,
"logLevel": "debug",
"pathRewrite": {"^/@apiproxy" : ""}
 }
}

I tried to alter my package.json file to

"start": "gulp serve.dev --proxy-config proxy.conf.json --color",

But it is not helping. If I pass the url directly to the varibale, i'm getting Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource error. I'm new to angular. please help.

1 Answers

First of all, we need to set up the proxy. Angular project already has a proxy.conf.js file for this. The following proxy script says if the frontend app makes the API call, which has /api in its path (ie. http://localhost:4200/api/), then convert that request into the target path.

This now means http://localhost:4200/api/ is proxied to http://localhost:8081/api/. One of the advantages of using a proxy is that it helps to hide the server details. In our case localhost:8080 is our server.

const PROXY_CONFIG = [
      {
        context: [
          "/api/"
        ],
        target: "http://localhost:8081/",
        changeOrigin: true,
        secure: false
      }
    ];

    module.exports = PROXY_CONFIG;

Run the angular project using the defined proxy

"scripts": {
    "start": "ng serve --proxy-config proxy.conf.js",
  }

In your service, simply use the relative url. For e.g

 public getClientConfig(): Observable<any> {
    return this.http.get(`/api/config`);
  }

When the request is being made from the frontend app, it becomes http://localhost:4200/api/config which is equivalent to http://localhost:8081/api/config.

I am not sure why you are using gulp. If you define the purpose of using this, I can provide you with additional information.

Lastly, regarding 'Access-Control-Allow-Origin', your server should whitelist the ip address of the server which is hosting the app. Following is the simple implementation in PHP based web servers.

<?php header('Access-Control-Allow-Origin: youripaddress'); ?>

I would suggest to go through https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more details regarding CORS and same origin policy. In addition, there are also some chrome extensions which will help to fix the CORS issue, which can be used for development purpose.

Related