Angular - blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *'

Viewed 2228

Getting error when I try to connect to a REST service that is in another domain. I understand it can be resolved by adding CORS in java rest service. But can it be possible by changing something in Angular side?

Access to 'http://someurl/RestWeb/getPerson' XMLHttpRequest at from origin 'http://localhost:4200' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *'

My Rest service: http://someurl/RestWeb/getPerson, all my rest service urls are like: http://someurl/RestWeb/SOMETHING

And my Angular url: http://someotherurl

After searching different articles, I already tried changing proxy.conf.json and package.json . Below re my changes, still I am getting same.

proxy.conf.json

{
  "/RestWeb": {
    "target": "http://someurl/",
    "secure": false,
    "changeOrigin": true  // I tried with and without this. No luck
  }
}

package.json

"start": "ng serve --proxy-config proxy.conf.json",

service:

  findAll(): Observable<Person[]> {
    return this.httpClient.get<string[]>('http://someurl/RestWeb/getPerson');
  }

run using:

npm start

As temporary counter measure, now I am testing my application in chrome browser using

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

SOLUTION

{
  "/RestWeb/*": {
    "target": "http://someurl",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}
2 Answers

It seems that webpack-dev-server's proxy misused.

proxy.conf.json

{
  "/api": {
    "target": "http://someurl.com/",
    "changeOrigin": true,
    "secure": false,
    "pathRewrite": {
      // replace `/api` with empty string, because real api path isn't contain 
      // `/api` segment
      // eg: http://localhost:4200/api/getPerson => http://someurl.com/getPerson
      "/api": ""
    }
  }
}

person.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class PersonService {
  constructor(private http: HttpClient) {}

  async getPerson() {
    return (
      this.http
        // you shouldn't use `http://someurl.com/getPerson` url directly,
        .get('/api/getPerson')
        .toPromise()
    );
  }
}

In your proxy configuration file, you are setting up the proxy for your http://localhost:4200/api*. So, the proxy will not work for /getPerson

Related