Search code examples
javascripthtmljsonfetch

Fetch() a local json file from public folder return an HTML file


My folder is as follows :

  • public > myJson.json
  • src > App.js and MyComponent.js

App.js

import React from "react";
import MyComponent from "./mycomponent";

const App: React.FC = () => {

  fetch("public/myJson.json")
      .then(res => res.json())
      .then(data => console.log(data));

  return <MyComponent>;
};

export default App;

MyJson.json

[
  {
    "a": "a",
    "b": "b"
  },
  {
    "a": "aa",
    "b": "bb"
  }
]

console error (with .json()):

localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

WHAT I HAVE TRIED SO FAR :

  • fetch with headers
headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
  • fetch("../public/myJson.json")
  • const response = await fetch()

Solution

  • You need to change

    fetch("public/myJson.json")
    

    to just

    fetch("/myJson.json")