fetch json local file get 404 not found

Viewed 1383

I have the structure of my project like this:

index.html ---folder js ---file data.json ---file index.js

In the data.json I have some data:

{
  "photographers":[
    {
        "name":"Mimi Keel",
        "id":243,
        "city":"London",
        "country":"UK",
        "tags":[
          "portrait",
          "events",
          "travel",
          "animals"
        ],
        "tagline":"Voir le beau dans le quotidien",
        "price":400,
        "portrait":"MimiKeel.jpg"
    }]
}

in index.js :

 fetch('./data.json',{
  headers : { 
    'Content-Type': 'application/json',
    'Accept': 'application/json'
    }})
   .then((response)=>{
  return response.json();
})
.then((data)=>{
  console.log(data);
})

I get the error

enter image description here

4 Answers

Try changing the path to: fetch('./js/data.json',{...

try using just data.json or try multiple options. Also, leave your JSON file outside of the current file.

Since it's in the same directory, you don't actually need a fetch - you can just use an import statement

import data from './data.json';

or

const data = require('./data.json');

I had the same problem and guess what Use this ideology:

  1. Your directory is not from the js file but from the html page running the js file
  2. Just write the directory as though the json file is being fetched from the html file running the script.‍‍
Related