angularaws-api-gatewayamazon-cognitounauthorizedchalice

No 'Access-Control-Allow-Origin' header is present on the requeste


- BUG: Access to XMLHttpRequest at 'https://*.execute-api.*.amazonaws.com/api' 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 requeste 
 
  • I have implemented Enable CORS on AWS API GATEWAY.
  • At the Backend we use chalice (Python), each API returns the body as follows:
Response(
            status_code=200,
            body={
                'name_pharmacy': data['name'],
                'pharmacy_id': data['id']
            },
            headers={
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'POST, PUT, GET, OPTIONS',
                'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With'
            }
        )
However we can't get past the CORS . error

Solution

  • To avoid CORS errors, you should proxy the calls so that the application always calls itself, then the proxy takes care of redirecting the calls.

    So, first we create the proxy.conf.json.

    touch proxy.conf.json`

    Inside it we put an initial configuration, e.g:

    {
      "/api": {
        "target": "http://localhost:8080",
        "secure": false
      }
    }
    

    In the package.json we modify the start command:

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

    Restart the application and we're there!

    here you can read about the proxy.

    Enjoy!