J Akhtar
J Akhtar

Reputation: 667

Ajax GET request data not being returned and gives CORS error

I know there are a lot of questions about CORS but I don't really understand how adding headers would apply to my in this case as I don't have one. I am learning coding through freecodecamp.com and this is an assignment I am doing an assignment which search articles on wikipedia whatever users type in the search box.

NOTE: I tried with jQuery and it does work that way but I want to do it with vanilla JavaScript for learning purposes.

Here is my code;

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);
@import url('https://fonts.googleapis.com/css?family=Arimo:400,700');



/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
  display: block;
}
body {
  line-height: 1;
}
ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}


/* CSS Reset end */








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;
}
.controls {
  width: 100%;
  margin: 65px auto;
}

input , #searchBtn {
  font-size: 40px;
  font-weight: bold;
  padding: 10px 15px;
  outline: none;
  border: none;
  
}

input {
  border-bottom: 3px solid #84ac47;
  width: 70%;
  background: transparent;
  color: #fff;
}

#searchBtn {
  background-color: #84ac47;
  color: #fff;
  border-bottom: 3px solid #58742F;
  width: 25%;
}

#randomBtn {
  outline: none;
  border: none;
  background: #fff;
  text-align: center;
  padding: 10px 15px;
  margin: 50px auto;
  color: #84ac47;
  font-size: 40px;
  width: 100%;

}


ul {
  list-style-type: none;
  margin: 0;
}

ul:before, ul:after {
  -webkit-margin: 0;
}

li {

  margin-bottom: 15px;
  font-size: 30px;
  font-weight: bold;
  background-color: #84ac47;
  padding: 15px 10px 15px 5px;
  
}

a {
  text-decoration: none;
  color: #fff;
}


.container {
  clear: both;
  
}
<!DOCTYPE html>

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" type="text/css" href="wikiviewer.css">
  <title> Wikipedia Viewer </title>
</head>
<body>
  
   
  
    
  <div class="container">
     <h1> Wikipedia Viewer </h1>
      <div class="controls">
        <input type="text" id="searchBox">
      </div>
  </div>
  
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="wikiviewer.js"></script>
</body>
</html>

Upvotes: 0

Views: 667

Answers (2)

qlown
qlown

Reputation: 527

Just add origin=* in your URL parameters, like so:

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

And then Wikipedia should give you a response with the proper headers, and your browser will accept to load the results.

I tested it with your code. It works, with that single change.

Borrowing from this answer:

to trigger the new behaviour, you need to specify origin=* in your url params. This is currently buried in the T62835 discussion and is not stated in the documentation yet.

While I'm at it, I'd recommend creating the XMLHttpRequest inside the function, to get a new one each time you query the service.

Here is a runnable example based on your code (but simplified to the relevant parts):

// Notice '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>

Upvotes: 3

John Haugeland
John Haugeland

Reputation: 9678

So, adding headers is the correct answer.

CORS is the set of rules that tells a browser "this endpoint is allowed to be hit by whomever."

Your endpoint needs to add the CORS headers that say "yes, it's perfectly cool for some other webpage to use me." Otherwise, when this address hits that other unrelated address, the browser rules say "no, this is shenanigans, put a stop to it."

You need Access-Control-Allow-Origin: * (or replace the * with the specific inbound address, if you prefer.)

Edit: some guy points out that you buried deep in your text that you were hitting wikipedia. If you had googled "wikipedia cors," you would have gotten their instructions.

Upvotes: -1

Related Questions