0

I'm just starting to learn javascript and I just ran into an error which I am unable to fix. I have a link which leads to a json file containing a link to an image which I want to use as the background for a website. I can access the json from my browser without any problems, but when I try to do it using javascript (code is below) I get the error CORS header ‘Access-Control-Allow-Origin’ missing. From what I have read this means that the server does not allow clients operating within the current origin to access the content. However, this confuses me since I can access the content from my browser. Can the server see in the http request what kind of client that is sending the get request? In summary, I'm confused about the origin of this error and am wondering if there is a way to solve it.

The code used to make the request:

    function get_link() {
        const url = "http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1";
        const http = new XMLHttpRequest();
        http.open("GET", url);
        http.send();
        http.onreadystatechange=(e)=>
        console.log(http.responseText)
    }

When I visit the url using my browser I see a json file, but when I send a get request using the XMLHttpRequest() function I get the error CORS header ‘Access-Control-Allow-Origin’ missing with code 200. Why is there a difference and how can I fetch the json file to my javascript program?

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
acke
  • 13
  • 3
  • 1
    It's the browser blocking the resource. CORS is a browser security feature to protect the user/visitor. It doesn't protect the resource on the server. – jabaa Jun 13 '23 at 16:04
  • 1
    Does this answer your question? [Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i) – jabaa Jun 13 '23 at 16:05
  • Thanks a bunch, I think I understand the issue a bit more :D It seems to me as if what i'm trying to do (make a get request to an external resource) is impossible using embedded javascript, and that I would need to have some kind of back end to perform this. Is this correct? – acke Jun 13 '23 at 16:16
  • Yes, that's correct. – jabaa Jun 13 '23 at 16:25

0 Answers0