Unexpected CORS error when fetching data with Ajax GET method

I have a question regarding CORS that I hope someone can help me with. I am currently working on an assignment for freecodecamp.com where I need to create a Wikipedia article search based on user input. However, I am struggling to understand how adding headers would apply in my case since I don't have any. I have attempted to use jQuery, which works, but I want to achieve this using vanilla JavaScript for learning purposes.

UPDATE: Here is the JavaScript code I have been working on:

var url, searchBox, searchText;
url = 'https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=10&search=';
searchBox = document.getElementById("searchBox");
var request = new XMLHttpRequest ();

function requestData ( e ) {
  var str = e.target.value;
  request.open("GET" , url + str );
  request.onreadystatechange = function(){
    if ( request.readyState === 4 ) {
      if ( request.status === 200 ){
        console.log(request.responseText);
      }
      
      else {
        console.log("Server returned a status code of " + request.status);
      }
    }
  };
  request.send(null);
}

searchBox.addEventListener("keyup" , requestData);

In addition, here is the CSS code I have used for styling:

@import url('https://fonts.googleapis.com/css?family=Arimo:400,700');

/* CSS Reset */
body {
  max-width: 960px;
  width: 100%;
  margin: 0 auto;
  font-family: 'Arimo', sans-serif;
  background: #000;
  color: #fff;
}

h1 {
  text-align: center;
  font-size: 72px;
  font-weight: 700;
}
/* More CSS styles included... */

If you can provide any insight or guidance on how to handle CORS and improve my code further, I would greatly appreciate it. Thank you!

Answer №1

To include origin=* in your URL parameters, simply add it like this:

var url = 'https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&datatype=json&limit=10&search=';

By doing so, you will receive a response from Wikipedia with the necessary headers for your browser to load the results.

I have personally tested this modification on your code and can confirm that it works flawlessly.

Quoting from a helpful response:

In order to activate this new functionality, it is crucial to specify origin=* in your URL parameters. Although this information is currently part of the T62835 discussion, it has not been officially documented in the documentation yet.

Additionally, I suggest creating the XMLHttpRequest inside the function to ensure a fresh object for each service query.

Below is a simple example based on your original code (with only the relevant parts included):

// Pay attention to the inclusion of 'origin=*' in the URL:
var url = 'https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=3&origin=*&search=';
var searchBox = document.getElementById("searchBox");

function requestData() {
  var str = searchBox.value;
  var request = new XMLHttpRequest();
  request.open("GET" , url + str );
  request.onreadystatechange = function(){
    if ( request.readyState === 4 ) {
      if ( request.status === 200 ){
        console.log(request.responseText);
      }
      else {
        console.log("Server returned a status code of " + request.status);
      }
    }
  };
  request.send(null);
}
<input type="text" id="searchBox" value="penguins">
<button id="searchButton" onclick="requestData()">Search</button>

Answer №2

It's important to add headers in order to allow CORS.

CORS, which stands for Cross-Origin Resource Sharing, is a set of rules that inform browsers about which endpoints can be accessed by external sources.

To prevent issues when one address tries to interact with another unrelated address, it is necessary to include CORS headers signaling that the endpoint is open for use by other webpages.

Specifically, you need to include Access-Control-Allow-Origin: * in your headers, or specify a specific inbound address if preferred.

Additionally, if you were trying to access Wikipedia and facing CORS issues, searching "wikipedia cors" would have led you to their instructions on how to resolve this problem.

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

Converting XML to JSON object by formatting string into scientific notation

I am facing an issue where a specific XML tag value is being converted to scientific notation when parsed into a JSON object. The original value is "09031454866678e6", but it gets transformed into "9.031454866678E6". Is there a way to ...

Sending the `<path>` wrapped in quotes to `<SvgIcon>` is resulting in the SVG not rendering

When I try to use the Material-UI's SvgIcon component, the <path> element is surrounded by quotes, which is preventing the SVG from rendering properly. https://i.stack.imgur.com/InDRt.png I'm currently working in Storybook within an MDX f ...

`Issues with AJAX PHP file upload`

I've been working on an AJAX PHP upload script, but I'm facing some issues. Once the user selects an image to upload, it should display in the specific div container specified in my javascript file (which is working fine). However, I believe ther ...

What could be causing this issue where the call to my controller is not functioning properly?

Today, I am facing a challenge with implementing JavaScript code on my view in MVC4 project. Here is the snippet of code that's causing an issue: jQuery.ajax({ url: "/Object/GetMyObjects/", data: { __RequestVerificationToken: jQuery(" ...

What is the best way to add to a variable in jQuery?

I have the following piece of code: var golden_site = '<div id="golden_site"></div>'; $('.form_content').append(golden_site); var lookup = '<input type="text" name="lookup" value="test">'; Can anyone explai ...

How come my Bootstrap tooltip title only updates once when I use the keydown event in jQuery?

My goal is to provide users with a character count for text inputs and textareas based on a maximum limit. To achieve this, I have added tooltips to elements with a data-maxlength attribute. I update the tooltip for text inputs to display the current lengt ...

Removing comments and extra space from multi-line regular expressions in YAML format

Is there a way to write a regular expression in YAML across multiple lines and when converted to JSON, it appears as a single line without any extra spaces or comments? I have followed the instructions outlined in the VSCode documentation to write a multi ...

Looking to fill a text field with email addresses by selecting checkboxes for various towers

I have 4 towers and I need checkboxes for each of them. Upon checking any combination of them, the 'txtNotifTo' textbox should be populated with the respective group of email IDs for each tower selected. Could you please assist me in identifying ...

How can regex be utilized to convert "==", "equals" from JSON to Python and execute the standard comparison operator?

I'm looking to retrieve the comparison operator == from a json file in order to compare s1==s2 in my Python script. Instead of directly assigning the comparison operator, I want to fetch it from the json data. def something(): s1=“Search_string ...

Is it possible for me to modify a JSON property within an OData response?

I've developed a model for use with OData, but I need to customize the property names in the JSON output. Here is my current model: public partial class Z_TESTE_DATA { [Key] public decimal DATA_ID { get; set; } public DateTime DATA_DATE ...

fullcalendar adjusting color while being moved

Currently, I have implemented a fullcalendar feature that displays entries for multiple users with different colored calendars. However, there seems to be an issue when dragging an entry to another date - the color reverts back to default. Below is an exa ...

Laravel encountered an error: MethodNotAllowedHttpException occurred without a message

When attempting to submit a form using Ajax, I encounter the following error: MethodNotAllowedHttpException No message. It seems like the issue lies in the routing, as it works fine when tested without Ajax. Below is my Ajax code: $.ajax({ met ...

Insight into AJAX Glitches and Strategies for Avoiding Them

My project is approximately 5 years old and written in VB.NET. I often encounter difficulties with the VB compiler swallowing errors, especially since the project is quite large and involves a lot of AJAX code. Whenever I start debugging this project, I u ...

What is the best way to indicate progress as the canvas resizes an image?

Is there a way for me to access progress updates? My main focus is on receiving progress information, regardless of how it will be displayed. I may choose to use a progress bar in the future, but my current inquiry pertains solely to obtaining the data it ...

Is it possible for index.html to reference a .js file in an Angular.js 1.x version?

Authorized users are allowed to access the menu items. While User A requires the menu_1.js file, User B does not need it and should not have access to it. I am trying to determine how to include required js files in index.html for an angular.js version 1 ...

Retrieve the data object in VueJS

(Regarding a currency conversion tool) In order to accurately convert currencies, I am looking to access an object structured like this: rates: AUD: 1.708562 SGD: 1.546211 When retrieving these rates from an API, they are not always in the desired o ...

How to use Python and JavaScript to make a WebElement visible in Selenium

I am currently facing an issue with uploading a PNG file using Selenium. The input element necessary for the upload process is visible to the user but not to Selenium. Following the suggestions in the Selenium FAQ, I tried using JavaScriptExecutor as shown ...

Tips for managing input for objects in Vue when the object hasn't been declared yet?

<input type="text" v-model="object[obj]"> Output: object:{'obj1':value} Desired outcome after input is added: object:{'obj1':{'prop1':value,'prop2':value}} <input type="text" ...

Enhancing JavaScript Asynchronous Programming with EventLoop and async/await

Exploring the intricacies of how JavaScript processes asynchronous methods led me to dive into async/await. In an effort to gain a complete understanding, I crafted the following example: async function first() { console.log(9); await Promise.resolv ...

Unable to trigger jQuery .click event

Having recently delved into the world of AJAX, jQuery, and JavaScript, I am facing a challenge that I believe is rooted in a simple oversight on my part. Expressing this issue can be quite perplexing, but I'll do my utmost to articulate it clearly. I ...