Currently attempting to retrieve a response from the Wikipedia API on Codepen. The expected reply should be in json format, which I plan to display using console.log.
However, when checking the console, I encounter an error:
Cross-Origin Request Blocked: The Same Origin Policy prevents access to the remote resource at https://en.wikipedia.org/w/api.php?action=opensearch&search=earth&format=json. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Despite reading extensively about CORS and Allow-Origin recently, implementing this concept is proving to be challenging for me :)
An interesting observation is that even though the console displays an error message, inspecting the actual response in the Network tab of developer tools reveals the complete json structure!
I would appreciate any insights or explanations on how is this phenomenon possible?
For the Codepen link, click here
var xhrObject = new XMLHttpRequest();
xhrObject.onreadystatechange = function() {
if (xhrObject.readyState === 4 && xhrObject.status === 200) {
console.log(xhrObject.responseText);
}
};
xhrObject.open(
"POST", "https://en.wikipedia.org/w/api.php?action=opensearch&search=earth&format=json", true
);
xhrObject.send();
Your assistance is greatly appreciated