Ad

Unable To Correctly Specify Headers For CORS Request

- 1 answer

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?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad