A
A
A person from Kazakhstan2021-05-13 08:56:58
AJAX
A person from Kazakhstan, 2021-05-13 08:56:58

Problem with fetch, what should I do?

Created (for training) on ​​a free hosting site type
Uploaded some json there: https://facejsonserver.000webhostapp.com/data.json
And I make a request:

fetch('https://facejsonserver.000webhostapp.com/data.json ')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  });


I get the error : Access to fetch at ' https://facejsonserver.000webhostapp.com/data.json ' from origin ' 127.0.0.1:5500 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

What should I do on my host or somewhere else to still be able to parse json ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-05-13
@LenovoId

You can pick up the file only "inside" the hosting. If it is possible to execute PHP, then you can use it to set up CORS and return the contents of the file.
Something like this:

<?php
  $filename = "data.json";

  header("Access-Control-Allow-Origin: *");
  header("Content-Type: application/json");

  if (file_exists($filename)) {
    print(file_get_contents($filename));
  } else {
    print(json_encode([]));
  }
?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question