-3

When I send request to my API Gateway with Angular I have this error :
*Access to XMLHttpRequest at 'https://example.com' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.*

And if I add 'Access-Control-Allow-Origin':'*' I have this one :
*Access to XMLHttpRequest at 'https://example.com' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.*

But the same request works perfectly with CURL, web browser and another mobile app (Flutter).
I tried to enable (with Access-Control-Allow-Origin:'*') and disable CORS in API Gateway but the problem remains the same.
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class mainService {
  constructor(private http: HttpClient) {}

  getAll() {
    return this.http.get<any>("https://example.com", 
      {
        headers: HttpHeaders({'Access-Control-Allow-Origin':'*'})
    });
  }
}
Kyshio
  • 55
  • 4

1 Answers1

-1

As mentioned in MDN's description of CORS

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.

Your curl, web-browser, and flutter application are not calling your backend API by script. Only your Angular applications using XMLHttpRequest to fetch data. To fix this you need to allow Cors from your backend application

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
vaibhav shanker
  • 173
  • 2
  • 10