-1

I am looking at an example as part of my course, we have recreated a basic Axios GET request from the ground up, The only issue is that the API url is returning an error due to CORS protection like so.

**index.html:1 Access to XMLHttpRequest at 'https://www.geojs.io/docs/v1/endpoints/country/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.**

I am looking on how to add the appropriate header to my XHR request to allow me to access the data but to no look, the code I have written (word for word copied from the example given in the lecture can be found beneath, my attempt to add the CORS header is included but commented out. Your help is as always most appreciated.

 //lets now recreat an Axios.get request from scratch 

//so far we have defined our function which we will pass a url as a parameter 
const request = new XMLHttpRequest();

//initialized request variable as a new XHR request

request.onload = function(){
    if(request.readyState !== 4 ) return;
    //if the request ready state does not reach stage 4 (final) we exit the function

    if(request.status >= 200 && request.status < 300 ){
        console.log("it worked, " + request)
    } else {
        console.log("ERROR!")
    }
}

request.onerror = function handleError() {
    console.log("NETWORK ERROR")
    request = null;
};

request.open('GET', 'https://www.geojs.io/docs/v1/endpoints/country/')
//request.setRequestHeader('Access-Control-Allow-Origin', '*')

request.send()
  • 1
    "I am looking on how to add the appropriate header to my XHR request " — The server which has the data needs to grant permission to the JavaScript that wants to read the data. It would be pointless if it was the other way around!! – Quentin Aug 16 '23 at 10:16
  • OK, I see, Could I ask you kindly if you have any information on how to achieve this? – Sean.realitytester Aug 16 '23 at 10:18
  • I refer you to the duplicate question. – Quentin Aug 16 '23 at 10:20

0 Answers0