Why is Access-Control-Allow-Origin getting removed after I make a successful call to my API

Viewed 63

I'm using an API set up by AWS API Gateway. I can make one successful call to this API. When I try to make another call, I get this error:

Access to XMLHttpRequest at 'url' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The response header has the access-control-allow-origin: * present in the first call, but it gets removed in the second call and I'm not sure why.

This is the successful API call XHR and Preflight response

Successful Preflight:

enter image description here

Successful XHR:

enter image description here

This is the failed API call XHR and Preflight response

Failed XHR:

enter image description here

Failed Preflight

enter image description here

As you can see in the failed XHR response, access-control-allow-origin is gone. I made this call very shortly after I made the first call. It doesn't make any sense to me how the first call has the origin header but the second one doesn't.

This is the ajax call I use to hit the API.

 $.ajax({
            url: `url`,
            method: 'GET',
            contentType: 'application/json',
            error: function (xhr) {
                if (xhr.status === 504) {
                    modelApi()
                    $('.overlayMessage').text('Server not responding, trying your search again. Please do not refresh the page')
                }
                if (xhr.status === 502) {
                    $('#overlay').fadeOut()
                    alert('No data was returned for your current search criteria. Please try selecting a different meter or date range')
                }
            }
        })

I also have CORS enabled on the API using the console in API Gateway. I'll post a picture of the cors config.

enter image description here

The docs also say that you should be sending the response to the server as well. I have that set up in the lambda function like this.

def get_model_lambda_handler(event,context):
    try:
        kwargs = event['params']['querystring']
        body = model.OLSRegression(**kwargs,download_data=True).run(preprocess=True)
        body = json.dumps(body,ignore_nan=True,cls=NumpyEncoder)
        response = {
            'statusCode': 200,
            'body': body,
            'headers': {
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'OPTIONS,GET',
                'Content-Type': 'application/json',
            },
        }
        return response

I think I have everything set up correctly to allow CORS. So I have no idea why I can only make one successful call. If anyone has any advice on what's going on it would be greatly appreciated.

0 Answers
Related