Cross origin request in javascript

Cross origin request in javascript
0.0 0

#1

I wanted to make a get request to wikipedia. But CORS policy is been violated.What i was doing is this…

function searchAuthor(element)
{
	var authorname=$(element).text();
	var ourrequest = new XMLHttpRequest();
	ourrequest.open('get','https://en.wikipedia.org/wiki/'+authorname);
	ourrequest.onload=function()
	{
		console.log(authorname);
	}
	
	ourrequest.send();
}

What i have tried

function searchAuthor(element)
{
	var authorname=$(element).text();
	var url='https://en.wikipedia.org/wiki/'+authorname;
	makeCorsRequest(url);
}

// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
  return text.match('<title>(.*)?</title>')[1];
}

// Make the actual CORS request.
function makeCorsRequest(url) {
  // This is a sample server that supports CORS.

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  // Response handlers.
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = getTitle(text);
    alert('Response from CORS request to ' + url + ': ' + title);
  };

  xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
  };

  xhr.send();
}

But with no luck.
Any guidance will be helpful!
thanks!!


#2

I was able to get it to work with this:

let searchString = "apple"

let url = 'https://en.wikipedia.org/w/api.php? format=json&action=query&generator=search&gsrnamespace=0&gsrsearch=' + searchString + '&gsrlimit=10&prop=extracts&exintro&explaintext&exsentences=1&exlimit=max&origin=*'

var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)

xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 400) {
    var data = JSON.parse(xhr.responseText)
    console.log('data returned:', data.query.pages)
  } else {
    console.log('connected to wikipedia, but error')
  }
}

xhr.onerror = function() {
  console.log('cannot connect to wikipedia')
}

xhr.send()

I think it works find with CORS without any special handling.