6

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?

Prateek Gautam
  • 274
  • 2
  • 5
  • 23

2 Answers2

3

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.

0

This is normal and is for your safety. You don't want anyone being able to access or read your files through a browser.

You could run a local server to test your requests.

Here are some good options: https://stackoverflow.com/a/20578692/10115173

LCPunch
  • 29
  • 4