Click here to Skip to main content
15,886,773 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
when i execute my code and try to get data from server through ajax it give me this error

Access to XMLHttpRequest at 'file:///C:/Users/Dubai%20Computers/Music/web%20designing%20and%20development/ajax/lecture%201/data.text' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
data.text:1 Failed to load resource: net::ERR_FAILED


My javascript code are the following

let textbutton = document.querySelector('#text-btn');

textbutton.addEventListener('click', function () {

    //create ajax request
    let xhr = new XMLHttpRequest();
    //prefare request
    xhr.open('GET', './data.text', true);
    //send request
    add(xhr);
    function add(request) {
        request.setRequestHeader("Access-Control-Allow-Origin", "*"); request.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
    }
    xhr.send();
    //process request
    xhr.onload = () => {
        if (xhr.status == 200) {
            let data = xhr.responseText;
            console.log(data);
        }
    };

});


What I have tried:

i have try many method but its not fixing how to fix this error
Posted
Updated 14-Sep-20 22:00pm

1 solution

You're loading an HTML file directly from disk. There will be a lot of limitations when you do that, including the fact that you can't make any AJAX requests to load other files from disk.

You need to load your page from a proper web server. On Windows, you can either use IIS or IIS Express.
Install and Setup a Website in IIS on Windows 10[^]

In this case, you're not making a cross-origin request; you're just loading data from the same origin as the page. But if you were, you'd need to understand how the CORS headers work: they need to be sent by the remote server as part of the response. You cannot set them as part of the request, since this would bypass their primary purpose.
Cross-Origin Resource Sharing (CORS) - HTTP | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900