Cors error accessing Api

Asked

Viewed 491 times

0

I am trying to access a wikipedia service with JQ, but in returning Cors error, could someone help me with a code to access this service correctly.

Url: https://pt.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=google

error

Blocked cross-origin request: Same Origin Policy (Same Origin Policy) prevents reading the remote resource at https://pt.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=google. (Reason: CORS header 'Access-Control-Allow-Origin' is not present).

  • 1

    insert error to facilitate help.

  • but this cross-origin request is blocked: The same origin policy (Same Origin Policy) prevents reading the remote resource at https://pt.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=google. (Reason: CORS header 'Access-Control-Allow-Origin' is not present).

1 answer

2


This is a protection that browsers have, preventing a customer at another address to make a direct request on some site, unless it authorizes external traffic. In these situations, it is worth trying to use JSONP. In an AJAX request with Jquery it looks like this:

var request = $.ajax({
  url: "https://pt.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=google",
  method: "GET",
  dataType: "jsonp"
});
 
request.done(function( msg ) {
  console.log(msg)
});
 
request.fail(function( jqXHR, textStatus ) {
  console.log(jqXHR, textStatus)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • Damn that thing :( there is some kind of API service to do this ? I used one but stopped working.

  • 1

    Not that I know of. You would have to actually build an API... One output I use in my projects is to use Firebase Cloud Functions.

  • I got it, thank you very much.

  • 2

    I took a little time to see the Wikipedia API, and managed to pull on the client. Just use jsonp. Are you making the request with jquery ajax? If so, put dataType: 'jsonp'. Here worked normally

  • 1

    @Joãopedrohenrique I was just testing this now, you can put as an answer because it really works.

  • Done, Leandro. Thanks for the touch ;)

  • Our many thanks friend :D top

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.