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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With