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 個答案
1
已接受的答案

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
已回答 6 個月前
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
已回答 6 個月前
profile pictureAWS
專家
已審閱 6 個月前
  • 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

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南