problem when try to fetch data from json file

Viewed 223

I have some problems when I try to fetch the data, I didn't get response. I write the path correctly? I attached the part of the code and pic of my project hierarchy.

let transportation = [];


const init = () => {
  fetch('/data/transportationDataCheck.json')
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      transportation = data;
    }).then(() => {
      renderList(transportation);
    });
};

enter image description here

3 Answers

try this:

const data = require("../data/transportationDataCheck.json")
console.log(JSON.stringify(data));

Or you may try after changing little URL

let transportation = [];


const init = () => {
  fetch('../data/transportationDataCheck.json')
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      transportation = data;
    }).then(() => {
      renderList(transportation);
    });
};

You are trying to serve a static file with a fetch command, which inherently requires the file to be served by a server.

Someone had a similar issue here: Fetch request to local file not working

Depending on what type of file this is, you may not need to make a fetch. You could probably instead require the file:

var transportationDataCheck = require('./data/transportationDataCheck.json');```

Use ./ at the beginning of the path

fetch('./data/transportationDataCheck.json')
.then(response => {
  return response.json()
})
.then(data => {
  // Work with JSON data here
  console.log(data)
})
.catch(err => {
  // Do something for an error here
})

Related