Home > Mobile >  Error 'Access-Control-Allow-Origin' using AWS API Gateway
Error 'Access-Control-Allow-Origin' using AWS API Gateway

Time:05-27

I am trying to make an $ajax request (POST) from my client-side (javascript/browser) to my API (python/flask) through AWS API Gateway. However, I get an error : No 'Access-Control-Allow-Origin'.

I have no problem when I request my API from postman.

I cannot enable option jsonp in ajax on my client side since it doesn't work at all.

So, I've tried to enable cors on API Gateway but my route is a http proxy integration (Method ANY) so according to AWS Docs, I have to enable Cors in the app itself. So, I did it but that didn't fix the problem.

In my python/flask app i added this:

@app.after_request
def add_headers(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    return response

But it still doesn't work.

Any suggestion ?

CodePudding user response:

I believe you have a CORS error issue.

First, go to your API Gateway and go to your resource, for example /books, then click on Actions and click activate the CORS like this:

enter image description here

Then fill all the options like this:

enter image description here

The Access-Control-Allow-Headers should have this: 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'

Also in the response of your python code you should add this too:

"Access-Control-Allow-Methods", "*"

Just remember the * is usually used on dev, but you should add the domain where the request will come to the API

CodePudding user response:

Instead of using '*', try to set set the effective origin to the Access-Control-Allow-Origin header.

response.headers.add('Access-Control-Allow-Origin', request.headers.origin)
response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');

For most headers, the value '*' only counts as a special wildcard value for requests without credentials (requests without HTTP cookies or HTTP authentication information).

see Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Allow-Methods etc.

According to CORS and caching, you may also have to add the following header.

response.headers.add('Vary', 'Origin')

Further you may have to define xhrFields.withCredentials: true when submitting the request with $.ajax().

$.ajax({
   url: a_cross_domain_url,
   xhrFields: {
      withCredentials: true
   }
   ...
}); 
  • Related