Using JavaScript to access the Wikipedia API with the Access-Control-Allow-Origin feature

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

Answer №1

Ensure you add origin=* to the query parameters of your Wikipedia URL in order for the request to function properly.

In order to successfully make JavaScript Fetch/XHR requests to the Wikipedia API, it is important to include origin=* as part of the URL query parameters—as specified in the CORS-related documentation for the Wikipedia backend:

When making anonymous requests, set the origin query string parameter to * to allow requests from any location.

Therefore, the URL you should be using will look like this:

"https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=earth&format=json"

…or even simpler like this:

"https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=earth="

(It seems that you can leave out format=json since JSON output appears to be the default setting.)

Answer №2

One fascinating observation is that despite the error message displayed in the console, the actual JSON response can still be viewed in its entirety within the Network tab of the developer tools.

I am curious to know how this phenomenon is possible.

The purpose of the Same Origin Policy is to prevent unauthorized access by malicious parties like Mallary who may attempt to exploit the sensitive information stored in a user's browser. This protection ensures that only trusted sources have access to the data.

Mallary's JavaScript code is restricted from accessing data unless explicitly permitted by the website through mechanisms like CORS (Cross-Origin Resource Sharing).

Bob's website trusts Alice's browser with the data, allowing it to access the information securely. Mallary does not have the capability to tamper with the developer tools in Alice's browser.

Answer №3

If you're still experiencing issues after adding origin=*, give this a try instead using withCredentials = false:

var xhttp = new XMLHttpRequest();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&limit=5&origin=*&search=simple";
xhttp.onreadystatechange = function () {
    if (readyState == 4 && status == 200) {
        console.log(responseText)
    }
};
xhttp.open("GET", url, true);
xhttp.withCredentials = false;
xhttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhttp.send();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript function not executing

Within a panel in an UpdatePanel, there is both a dropdown list and a file upload control. The goal is to enable the Upload button when a value is selected from the dropdown and a file is uploaded. This functionality is achieved through a JavaScript functi ...

What happens when the user closes a notification in GetUIkIt 3?

Is there a way to detect when a UIKit notification has been closed? The UIkit notification plugin () mentions that it has a close event. Can this be utilized for notifications triggered programmatically as shown below? e.g. UIkit.notification({ mess ...

Using JSON format to pass variables in C# programming language

Is there a way to properly pass my variable within a JSON string like this? string name = "john"; string json = @"{ 'EmployeeName': name, 'EmployeeID': '123', } I ke ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

Having trouble resolving the signature of a class decorator when invoked as an expression with @Injectable in Angular

Error Message: Unable to resolve the signature of a class decorator when called as an expression. The argument type 'ClassDecoratorContext' is not compatible with the parameter type 'string | symbol | undefined'. After creating a book ...

JQuery is not able to render Hindi content properly

I am attempting to showcase some Hindi words using JQuery because these are essential contents that need to be displayed on every page of the website. Please note that this is a static website built with HTML and JQuery/JavaScript. Below is my JS file: in ...

Retrieve the JSON array value from the observable and pass the information to the frontend

Attempting to retrieve a JSON array from a json-server using observables, then passing the value to the frontend for search functionality on the received JSON array. Created a service and utilized HTTP get method to establish a connection with the server ...

Pressing a shortcut key will direct the focus to the select tag with the help of Angular

I was trying to set up a key shortcut (shift + c) that would focus on the select tag in my form when pressed, similar to how tab works. Here is the HTML code for my form's select tag: <select id="myOptions"> <option selected> Opti ...

When receiving a GET response after a server crash

Question: I am sending a Get request through Ajax every second and waiting for a response from the server. However, if my application crashes and I keep sending requests every second, I only receive a server timeout error (HTTP status code 502) with no oth ...

Issues with texturing in ThreeJS

I am currently working on a project in threejs that involves loading a .stl file. However, I have run into an issue where the loaded object automatically changes color from its original one. I would like to keep the original color of the object. What steps ...

Tips for creating case-insensitive query string values in angularjs?

After reading about the case sensitivity of query string keys from here, I realized my query pertains to the case sensitivity of query string values. Is there a way to make query string values case insensitive? Is it possible to receive the same result wh ...

Tips for toggling the visibility of a revolution slider based on current time using JavaScript

Currently, I am integrating the revolution slider into my WordPress website. My goal is to have the slider change according to the standard time of day. For instance, I want slider1 to display in the morning, slider2 at noon, slider3 in the evening, and sl ...

Combining a variable and a string within a property in JavaScript: Is it possible?

<TextField label="First Name" defaultValue="My name is" + ${name} /> In this code snippet, the variable name holds the actual name that needs to be concatenated with the string "My name is". However, when atte ...

Issue with Phonegap FileTransfer functionality

Currently, I am working on building a basic iPhone app using phonegap and jquery. My main goal is to be able to successfully upload images from my iPhone to a remote server. I attempted to achieve this by utilizing the phonegap FileTransfer feature, but ...

Storing information from a Json object into a Database (SQLite)

As a beginner in Android development, I am struggling to figure out how to save data retrieved from an HTTP request in JSON format into a SQLite database. Below is the code snippet that I have been working on: final ArrayList<HashMap<String, String ...

angular-ui-tab-scroll: Odd spacing between blocks and tabs, each separated individually

Greetings! I would like to express my gratitude for this wonderful library! However, I am encountering an unusual issue when trying to wrap a tabset with tabs that are included separately. This can be done either by adding individual tab elements manually ...

Tips for effectively directing JSON response to populate a table

I recently started learning ajax and I'm looking for some guidance. I'm currently working on fetching data through an API, and while I am able to see the response in the console, I'm struggling with targeting the specific data that I need to ...

Disabling GPS with HTML5/phonegap: A step-by-step guide

Looking to create a function that can toggle GPS on and off for both iPhone and Android devices ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

Unexpected Behavior: AJAX Response Does Not Append Desired Class

I'm currently developing a social networking site where users can post and comment on each other's posts. Upon initial page load, only two comments are displayed for each post, with the rest being hidden. Clicking on the "Load more" button reveal ...