-1

I have some simple code trying to make an ajax request. I tried using a .txt file and found a CORS error. I then tried using a php file using header("Access-Control-Allow-Origin: *"); because I heard this is the easiest way to allow all ajax calls on any browser. I have looked through many SO posts and have googled everywhere, and cant seem to find a solution. Here are my files. I will include the .txt file, but i already understand why that file isnt working.

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="button">Get Text File</button>
  <br><br>
  <div id="text">

  </div>

  <script>
    //create event listener
document.getElementById('button').addEventListener('click', loadText);

function loadText() {
  //create an object
  const xhr = new XMLHttpRequest();
  //open - type, url/file, async t/f
  xhr.open('get', 'sample.php', true);

  console.log('READYSTATE: ', xhr.readyState);

  //OPTIONAL - used for loaders
  xhr.onprogress = function () {
    console.log('READYSTATE: ', xhr.readyState);
  }

  xhr.onload = function () {
    console.log('READYSTATE: ', xhr.readyState);
    if (xhr.status == 200) {
      // console.log(this.responseText);
      document.getElementById('text').innerHTML = this.responseText;
    } else {
      document.getElementById('text').innerHTML = 'Not Found';
    }
  }

  xhr.onerror = function () {
    console.log('request error');
  }

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

</html>

sample.php

<?php
  header("Access-Control-Allow-Origin: *");

  echo "Some Lorem ipsum text";
?>

sample.txt

lorem ipsum

Here is what the chrome console shows

READYSTATE: 1

ajax1.html:1 Access to XMLHttpRequest at 'file:///Users/macbookuser/Desktop/traversy/ajax/sample.php' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. ajax1.html:46 request error ajax1.html:56 GET file:///Users/macbookuser/Desktop/traversy/ajax/sample.php net::ERR_FAILED

Citizen Patrol
  • 260
  • 3
  • 13
Dylan T
  • 139
  • 11

1 Answers1

0

It's a fairly self explanatory error, I think. Cross origin requests are only supported for a specific list of protocols (the word that the url starts with, before the ://) cited in the error message and you're requesting a file from a url that doesn't start with one of the permitted protocols: file:// is not in the listed protocols;

How did it happen? Well, the url in your html is relative, and because you've just straight opened the html file (on your local disk) in a web browser, the url in the browser address bar is showing 'file://...' and any requests the Ajax makes to relative URLs will also use this protocol, so it's using file protocol not http. Cross origin requests cannot function in this way.

Host your files on a web server, open the http url to the html file in your browser and try again

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • thank you. That actually makes perfect sense. I was kind of seeing that the error was due to a local file, but thought the php header would fix that. Do you think a static server like netlify would work? – Dylan T Mar 01 '20 at 08:55
  • Or I guess using xampp should work? – Dylan T Mar 01 '20 at 09:04
  • You can probably get a free webserver from Azure or AWS etc for testing purposes, so why not make a mimic of a production environment without the headaches of running your own sevrer? But any local server that listens on a port and will serve the html file will be fine. You basically just have to get to a situation wher ethe URL in your browser starts with `http`, not `file` – Caius Jard Mar 01 '20 at 11:45