Fetch API - CORS error

0

Dear, I have an application in javascript, using fetch API to fetch the information in a static file .json . It works normally when used on a live server (localhost) in the VsCode editor. But when it does not run on a local server, it returns CORS error. I would like to understand why this occurs and how could I resolve it?

document.getElementById('getUsers').addEventListener('click', getUsers);

function getUsers() {
   fetch('users.json')
   .then((res) => res.json())
   .then((data) => {
  let output = '<h2>Users</h2>';
  data.forEach(function(user) {
     output +=
     '
     <ul class="list-group mb-3">
     <li class="list-group-item">ID: ${user.id}</li>
     <li class="list-group-item">Name: ${user.name}</li>
     <li class="list-group-item">Email: ${user.email}</li>
     </ul>
     ';
  });
  document.getElementById('output').innerHTML = output;
   })
}
<!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">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css">
  <title>Document</title>
</head>

<body>

  <div class="container">
    <h1 class="display-4 mb-4">Fetch API </h1>
    <div class="d-flex">
      <button class="btn btn-primary mr-4" id="getText">Get Text</button>
      <button class="btn btn-success mr-4" id="getUsers">Get JSON</button>
      <button class="btn btn-warning mr-4" id="getPosts">Get API DATA</button>
    </div>
    <hr>
    <div id="output"></div>
  </div>

  <script src="js/connection-index1.js"></script>

</body>

</html>

Error:

Fetch API cannot load file:///Users/rodeghiero/Documents/developer/js-ajax-es6/src/users.json. URL scheme must be "http" or "https" for CORS request.
getUsers @ connection-index1.js:19
    
asked by anonymous 29.11.2017 / 18:13

0 answers