Solving HTTP GET Failures: 'Origin Not Allowed by Access-Control-Allow-Origin' in AWS from jQuery or XMLHttpRequest

When working with Amazon Web Services (AWS) and attempting HTTP GET requests from jQuery or XMLHttpRequest, you may encounter an error: ‘Origin is not allowed by Access-Control-Allow-Origin’. This error is related to the CORS (Cross-Origin Resource Sharing) policy, which is a security measure implemented in web browsers to prevent requests to different domains.

Solving HTTP GET Failures: “Origin Not Allowed by Access-Control-Allow-Origin” in AWS from jQuery or XMLHttpRequest

When working with Amazon Web Services (AWS) and attempting HTTP GET requests from jQuery or XMLHttpRequest, you may encounter an error: “Origin is not allowed by Access-Control-Allow-Origin”. This error is related to the CORS (Cross-Origin Resource Sharing) policy, which is a security measure implemented in web browsers to prevent requests to different domains.

In this post, we’ll delve into the cause of this issue and walk you through the steps to resolve it, enabling successful HTTP GET requests from jQuery or XMLHttpRequest.

Understanding CORS

The main culprit behind the error is the CORS policy. CORS is a mechanism that allows many resources (e.g., fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated.

When a web browser attempts to retrieve a web page from a domain different from its own, it makes a ‘cross-origin’ HTTP request. For security reasons, web browsers prohibit web pages from making requests to a different domain than the one the web page came from, unless the server supports CORS.

Mitigating the Error in AWS

AWS provides a way to set CORS headers on your S3 buckets. This allows you to specify which origins (domains) are allowed to access your resources.

To resolve the “Origin is not allowed by Access-Control-Allow-Origin” error, follow these steps:

  1. Navigate to your S3 Bucket on AWS: Log into your AWS console and navigate to the S3 service. Select the bucket that contains your resources.

  2. Open Bucket Permissions: In the bucket settings, click on the ‘Permissions’ tab.

  3. Edit CORS Configuration: Scroll down to find the ‘Cross-origin resource sharing (CORS)’ section and click on ‘Edit’.

  4. Update CORS Policy: In the CORS configuration editor, input the following policy:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "POST",
            "PUT"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]
  1. Save Changes: Click ‘Save changes’ to apply the new CORS policy.

Remember, the wildcard (*) allows all origins to access your resources. It’s a good starting point for debugging, but for a production environment, you should replace the asterisk with your domain to minimize potential security risks.

Fixing the Issue in jQuery or XMLHttpRequest

If you’re using jQuery or XMLHttpRequest to make the request, ensure that it’s set to send requests with credentials. Here’s how to do it:

jQuery

$.ajax({
    url: 'yourAWSUrl',
    type: 'GET',
    dataType: 'json',
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    success: function(data) {
        console.log(data);
    }
});

XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('GET', 'yourAWSUrl', true);
xhr.withCredentials = true;

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
}

xhr.send();

In both cases, withCredentials: true tells the browser to expose the response to the front-end JavaScript code and to send any cookies associated with the domain of the request URL.

Conclusion

The “Origin is not allowed by Access-Control-Allow-Origin” error is a common issue that developers encounter when dealing with HTTP requests in JavaScript and AWS. By understanding CORS and correctly configuring it in AWS and our JavaScript code, we can successfully execute our HTTP GET requests from jQuery or XMLHttpRequest.

Remember, security is crucial - so ensure to replace the wildcard with your specific domain in a production environment. Happy coding!


About Saturn Cloud

Saturn Cloud is your all-in-one solution for data science & ML development, deployment, and data pipelines in the cloud. Spin up a notebook with 4TB of RAM, add a GPU, connect to a distributed cluster of workers, and more. Join today and get 150 hours of free compute per month.