Home > Blockchain >  Angular proxy config not having any effect
Angular proxy config not having any effect

Time:03-16

I have a REST API backend running at http://localhost:8000/api, my Angular 13 app runs at http://localhost:4200. Naturally, I receive a CORS error when trying to query any endpoint of that backend.

So I tried to set up the Angular proxy. I added the file src/proxy.conf.json with the following content:

{
  "/api": {
    "target": "http://localhost:8000",
    "secure": false,
    "logLevel": "debug"
  }
}

After that, I added the following to angular.json:

"serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "proxyConfig": "./src/proxy.conf.json"
      },
      "configurations": {
        "production": {
          "browserTarget": "photon:build:production"
        },
        "development": {
          "browserTarget": "photon:build:development"
        }
      },
      "defaultConfiguration": "development"
    },

(I also added the proxyConfig node under "development" configuration, but no change.)

Now, when I run npm start, which triggers ng serve, I do not see that the proxy is set up at all in the console output - and the API request still receives a CORS error. I believe there should be some console output that shows that the proxy was set up, like so:

Proxy created: /api -> http://localhost:8080 (I saw this here.)

I have no idea why this is not working, this should be simple.

Edit: Here is the request function itself.

  get(url: string) {
    return fetch(this.apiUrl   url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(response => {
         console.log(response);
         return response.json();
      });
  }

The URL that this function receives is correct, I can see that in the debugger.

CodePudding user response:

Try the proxy config url without the leading dot "proxyConfig": "src/proxy.conf.json"

If you're using Node express you can add the cors middleware if hitting the server directly

Only calls made to the dev server will be proxied. If you're calling localhost:8000/api directly it won't work

You call localhost:4200/api, the Angular dev server receives the request, and proxies it to localhost:8000/api

  • Related