HTTP Get request is always blocked by CORS policy

0

Hi Team,

I always have issues with CORS errors. I create API Gateway and lambda function to handle the REST GET API. An HTTP get request sent from the javascript XMLHttpRequest object to the stage URL https://domain.execute-api.ap-northeast-1.amazonaws.com/resume/schema. However, the response json data can be obtained through the test results of postman, edge, and chrome browsers. Only http sent by javascript will be blocked by CORS policy.

The error message is as follows: { Access to XMLHttpRequest at 'https://domain.execute-api.ap-northeast-1.amazonaws.com/resume/schema' from origin 'null' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'vary:Origin' that is not equal to the supplied origin. ride.js:41

   GET https://domain.execute-api.ap-northeast-1.amazonaws.com/resume/schema net::ERR_FAILED 200 (OK)

}

The lambda code function has included some headers: response_body = { "statusCode": 200, 'headers': { 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET' }, "tableName": "resume", # Replace with your table name "schema": json.dumps(schema, indent=4) } return response_body

Test sender from postman provided:

var xhr = new XMLHttpRequest(); xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() { if(this.readyState === 4) { console.log(this.responseText); } });

xhr.open("GET", "https://domain.execute-api.ap-northeast-1.amazonaws.com/resume/schema");

xhr.send();

Any advice would be greatly appreciated!

Thank you!

Sean

2 Answers
1
Accepted Answer

To prevent the browser from sending non-standard and library-specific additions, I recommend using the Fetch API. In fact the $.ajax() method from jQuery that you are using is adding the X-Requested-With header - please see the jQuery documentation. Please either add the Access-Control-Allow-Headers: X-Requested-With to your Lambda code or just request your content with Fetch:

fetch(url).then(console.log)

By default, fetch will operate in the cors mode and will use the GET method, but if you want to set these yourself:

fetch(url, { 
    method: "GET", // GET, POST, PUT, DELETE, etc.
    mode: "cors", // cors, no-cors, same-origin
}).then(console.log)

Please note that

  • Fetch API is async. You need to await the promise it returns or use .then() to process the response further,
  • You used Access-Control-Allow-Origin: "*". If, in the future, you make a credentialed request, you can't use wildcards (*) as values of any of the Access-Control headers on the server side, as it won't be CORS-compliant. You will need to explicitly specify allowed headers/methods/origins.

Please consider accepting this answer if the issue got resolved. Thanks!

AWS
Piotrek
answered 6 months ago
0

Hi, it seems like you are encountering a CORS (Cross-Origin Resource Sharing) error when making an HTTP GET request from a local file system using the XMLHttpRequest object. The origin 'null' typically indicates that you are loading the HTML page via a file:/// URL, which triggers CORS restrictions for security reasons. Browsers apply the Same Origin Policy to local files, and loading resources from the local file system may not work as expected due to security measures.

Instead of loading the HTML page directly from the local file system, please set up a simple web server and test your application using http:// URLs. This will provide a more accurate security picture and is a common practice for local development.

More information about Access-Control-Allow-Origin header and why usage of null is discouraged can be found on MDN web docs.

Please let us know if you were able to solve your issue!

AWS
Piotrek
answered 6 months ago
profile pictureAWS
EXPERT
reviewed 6 months ago
  • Dear Piotrek,

    I try to use amplify to hold my website, but still got the CORS error: { Access to XMLHttpRequest at 'https://domain.execute-api.ap-northeast-1.amazonaws.com/resume/schema' from origin 'https://main.domain.amplifyapp.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'vary:Origin' that is not equal to the supplied origin.

    GET https://domain.execute-api.ap-northeast-1.amazonaws.com/resume/schema net::ERR_FAILED 200 (OK) }

    At the same time, we also did some experiments:

    Test sender provided by postman (javascript): var settings = { "url": "https://domain.execute-api.ap-northeast-1.amazonaws.com/resume/schema", "method": "GET", "timeout": 0, };

    $.ajax(settings).done(function (response) { console.log(response); });

    1. Use note.js to execute the sender to run Lambda Function URL -> Successfully obtained response
    2. Use note.js to execute the sender to run Lambda Function via API Gateway REST API -> Successfully obtained response
    3. Use HTML include the sender to run Lambda Function URL -> Successfully obtained response
    4. Use HTML include the sender to run Lambda Function URL(enable CROS) -> CORS error
    5. Use HTML include the sender to run Lambda Function via API Gateway REST API -> CORS error

    We suspect that the browser may have added an unmatched header to the java script http request. If you have a different opinion, I would be grateful if you could provide it.

    Thank you!

    Sean

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions