1

Hi I am trying to hit a AWS API gateway it's working fine on CURL but not working from JS Brocking for CROS policy. But from AWS I already enabled CROS

$.ajax({
        url: ApiURL,
        type: 'POST',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(hash),
        async: true,
        crossDomain: true,
        crossOrigin: false,
        headers: {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': '*',
        'Access-Control-Allow-Methods': 'POST'
        },

CURL method hit through AJAX

$.ajax({
        url: stripTrailingSlash(BASE_URL) + '/contact/send',
        type: 'POST',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(body),
        async: true,
        headers: {
            'X-CSRF-Token': csrfToken
        },

My api gateway POST structure like this

My lambda response I did like this

const response = {
statusCode: statusCode,

 headers:{ 'Access-Control-Allow-Origin' : '*' },
body: JSON.stringify({
  message: responceMessage,
  input: event,
}),
};
callback(null, response);

Error I am getting in my browser

1
  • If you are using "proxy request integration" your lambda should handle the CORS requests. Enabling CORS in api gateway doesn't make sense in that case. Commented Jan 23, 2019 at 5:57

1 Answer 1

4

It works in CURL because, CURL doesn't send OPTIONS request, but browser sends it whenever you are making a CORS request.

Response to the OPTIONS request is what browser uses to check whether you are allowed to call the API.

When you enable CORS in API Gateway, it will add the following headers

'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'POST'

but if you enable Proxy Request Integration, API Gateway no longer modifies the response to add the headers. Hence, it won't work unless your lambda function adds these header by itself.

Sign up to request clarification or add additional context in comments.

4 Comments

Tx for ur answer. but I already did that and my api gateway is not using proxy i.sstatic.net/puJf5.png
can you show what response you are getting in the browser for the OPTIONS and POST request?
Here is the error I am getting i.sstatic.net/lE2lA.png and my request looks like this i.sstatic.net/zvVSC.png
you are not supposed to add 'Access-Control-Allow-Origin': '', 'Access-Control-Allow-Headers': '', 'Access-Control-Allow-Methods': 'POST' in request. Remove it, it should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.