kurtgn
kurtgn

Reputation: 8710

unable to correctly specify headers for CORS request

I created an AWS API Gateway endpoint that needs to be called from the browser. This is a simple jquery ajax post:

$.post(
    'https://jhntqqm19l.execute-api.us-east-1.amazonaws.com/dev',
    {}
  )

(fiddle here: https://jsfiddle.net/7cfyr1mL/)

The browser says that the endpoint does not return appropriate CORS headers:

 No 'Access-Control-Allow-Origin' header is present on the requested resource.

however when I request this endpoint from python I see that the headers do exist:

# testing OPTIONS request
>>> res = requests.options('https://jhntqqm19l.execute-api.us-east-1.amazonaws.com/dev')
>>> print(res.headers)
200
>>> print(res.status_code)
{'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', ...}





# testing POST request

>>> res = requests.post('https://jhntqqm19l.execute-api.us-east-1.amazonaws.com/dev', json={})
>>> print(res.headers)
{'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', ...}
>>> print(res.status_code)
400

what is wrong with my headers? How do I change them so that the browser is happy?

Upvotes: 0

Views: 57

Answers (2)

Quentin
Quentin

Reputation: 943099

Your server-side code throws a 500 error and doesn't set the Access-Control-Allow-Origin header if it gets a POST request which isn't JSON encoded.

jQuery POST uses standard form URL encoding by default, so you have to override that.

$.ajax(
  'https://jhntqqm19l.execute-api.us-east-1.amazonaws.com/dev',
  { contentType: 'application/json', data: JSON.stringify({}), method: "post"}
);

You'll also need to change the server-side code to allow a preflight request as currently, you don't allow JSON formatted requests with CORS.

Upvotes: 2

Shweta Valunj
Shweta Valunj

Reputation: 158

In server side code (python in your case) you will have to enable few things along with header

'Access-Control-Allow-Origin': '*'

You can refer to https://www.codecademy.com/articles/what-is-cors and search how to apply cors based on your framework.

The browser makes an OPTIONS call before it actually makes any call to your application. Make sure it is enabled depending on your application. For example allowedHttpHeaders, allowedHttpMethods, allowedOrigins.

Upvotes: 1

Related Questions