Search code examples
javascripthtmlservercorslocal

How to get server content from local html file?


In detail, I want to access Wikipedia from a local HTML/JS file. When requesting a file by jQuery:


$.getJSON('http://www.wikipedia.org', function(data){
    alert(data);
});

I get Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at wikipedia.org Is there any way to work around CORS ?


Solution

  • sure. https://allorigins.win/ I've used this workaround plenty of times

    the way it works is that it gets these contents via its own API, and for free use, you can reference their results by pulling data.contents.

    using vanilla javascript/fetch statement

    fetch(`https://api.allorigins.win/get?url=${encodeURIComponent('https://wikipedia.org')}`)
                    .then(response => {
                      if (response.ok) return response.json()
                      throw new Error('Network response was not ok.')
                    })
                    .then(data => console.log(data.contents));
    

    Using jQuery .getJSON

    $.getJSON('https://api.allorigins.win/get?url=' + encodeURIComponent('https://wikipedia.org'), function (data) {
                      alert(data.contents);
                  });