2
votes

This is pretty much a known standard error but unable to fix the same using existing Stackoverflow posts.

XMLHttpRequest cannot load https://myserver.com/context/
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://www.otherwebsite.com' is therefore not allowed access.
The response had HTTP status code 405.

Following is the code I have -

function setHeader(xhr) {
    xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
}

var url = "https://myserver.com/context/";
$.ajax({
    url: url,
    type: 'GET', dataType:'json',
    success: function(data) {
        _this.question(data.question);
        _this.questionId(data.questionId);
        _this.choices(data.choices);
    }, error: function() {
        console.log("ERROR in getting microquestion");
    },
    beforeSend: setHeader
});
1
Reading the error message: "No 'Access-Control-Allow-Origin' header is present on the requested resource."Teemu
I just realized what error was trying to point out. The issue was on the server side. that's what "requested resource" meant. Thanks to @sideshowbarker who explicitly pointed that out. Upvoting both of youcomiventor

1 Answers

1
votes

The “Response to preflight request… had HTTP status code 405.” message indicates, to start, the https://myserver.com/context/ endpoint needs to be configured to handle OPTIONS requests correctly—even if it may already be set to send the right CORS headers back for “normal” requests.

For more details about what’s happening, you can read the How to avoid the CORS preflight section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API — but the gist of it is, minimally, the server must respond to OPTIONS requests with a 2xx success status code.