0
Dear, I have a javascript application, 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.
However when not executed on a local server, it returns CORS error. I would like to understand why this occurs and how it could solve?
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
You are making an asynchronous request using protocol
file
? Have you tried running your application inside an HTTP server?– Woss
A while ago I tried to run as gitpages and also gave error, but the server localhost does not generate. Sorry but I do not know the protocol "file".
– Mário Rodeghiero
The protocol
file
, @Máriorodeghiero, is when you are running the file directly by it and not by a serverHTTP
. Look at the address that is returning in error:file:///Users/rod
...– Marcelo de Andrade
Got it @Marcelodeandrade ! I’ll wait and see if anyone has a solution to run with file protocol or on gitpages.
– Mário Rodeghiero