aryaman
aryaman

Reputation: 466

[CORS]:' Access-Control-Allow-Origin' not allowing to get a cross-domain JSON?

Actually, I want to get a JSON object from this url , I tried using XMLHttpRequest() in javascript but console logged this error: [CORS] The origin 'http://localhost' did not find 'http://localhost' in the Access-Control-Allow-Origin response header for cross-origin resource at 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN'.

But when I typed url in browser address bar, it loaded correctly! See the screenshot! enter image description here

See my javascript code:

    <script>
        var url='http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN';
        var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status === 200) {
    callback(null, xhr.response);
  } else {
    callback(status, xhr.response);
  }
};
xhr.send();
};
getJSON('http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN', 
function(err, data) {
  if (err !== null) {
    alert('Something went wrong: ' + err);
  } else {
    console.log(data);
  }
});

        </script>

Note: I can't control the server.

Upvotes: 2

Views: 4220

Answers (3)

Feng Zhang
Feng Zhang

Reputation: 1948

I got this error when playing with AWS serverless using S3 bucket. after adding below in S3/bucketname/permission/CORSconfiguration the following:

<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Upvotes: 0

Leonid Pyrlia
Leonid Pyrlia

Reputation: 1702

You can view the information on what CORS is here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

As to your problem, you can solve it by proxying your requests through services like https://cors.io. For example, run this in your console:

fetch('https://cors.io?http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN')
.then(res => res.json())
.then(data => console.log(data))

Please keep in mind that it's not ideal solution as your code will depend on a 3rd-party service in this case. Which is ok for some personal home projects, but not for big corporate ones.

Upvotes: 3

KRISHNA PATEL
KRISHNA PATEL

Reputation: 135

You can add https:// in the url instead of http://. This will fix your issue.

You can also open your chrome browser with

chrome.exe --allow-file-access-from-files --disable-web-security

in Windows Run.

Upvotes: 1

Related Questions