3

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

ROOT
  • 10,339
  • 5
  • 24
  • 40
code
  • 41
  • 1
  • 1
  • 6
  • Look in the console and/or network tab. What error do you get? – T.J. Crowder Mar 21 '20 at 11:30
  • I think you need to check the path is correct or not . to ensure that check browser network . just try with path ../data/transportationDataCheck.json – user3766508 Mar 21 '20 at 11:32
  • There are three problems with the code in the question, but neither of them is likely to be the root problem (though one of them might have pointed you to the root problem): 1. You're not checking for HTTP errors. This is a footgun in the `fetch` API (I write about it [here]()). Check `response.ok` in your first fulfillment handler to see if the HTTP request worked (sadly, `fetch` only rejects on *network* errors, not HTTP errors). 2. There's no reason to have the last two fulfillment handlers, just use one. 3. You're not handling rejection. FWIW: https://pastebin.com/hPDUU25i – T.J. Crowder Mar 21 '20 at 11:32
  • what do you get if you try the path in the URL directly `APP_URL/data/transportationDataCheck.json`? – ROOT Mar 21 '20 at 11:38

3 Answers3

0

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);
    });
};
Pushpendra Kumar
  • 1,483
  • 1
  • 13
  • 20
0

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');```
buttface64
  • 121
  • 4
-1

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
})