Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to XMLHttpRequest at 'file:///sample.txt' from origin 'null' blocked by CORS policy: CORS are only supported for protocol schemes [duplicate]

I'm new in AJAX and currently learning very basics of it. In my html file on hitting the submit button I'm just trying to log the text of a text file which is in the same directory of html file itself. But instead I'm getting a error

Access to XMLHttpRequest at 'file:///D:/Front_end_files/AJAX/sample.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

here's my Ajax-1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax-1 Text file</title>
</head>
<body>
        <button id="btn">Click Me</button>

        <script>
            document.getElementById('btn').addEventListener('click',loadtext);

            function loadtext(){

                let xhr = new XMLHttpRequest();
                console.log(xhr);

                xhr.open('GET', 'sample.txt', true);

                xhr.onload = function(){
                    if(this.status == 200){
                        console.log(this.responseText);
                    }
                };

                xhr.send();
            }
        </script>
</body>
</html>

Can somebody tell me what am I doing wrong here or is it something new feature with chrome and firefox?

like image 470
Prateek Gautam Avatar asked Nov 15 '19 15:11

Prateek Gautam


Video Answer


1 Answers

This behaviour is discouraged because it provides a security breach in your computer, we don't want to be able to do AJAX request into our files, that would expose our local system to the web.

As they've stated previously, CORS doesn't support local file:// access so you'll have to find a way around, a simple one would be to use python to serve a simple HTTPServer and serve the file there, for example:

python -m SimpleHTTPServer 8080

And this will server your current working directory as a small webserver.

like image 166
Alejandro Vicaria Avatar answered Oct 30 '22 17:10

Alejandro Vicaria