2

I'm trying to make a fetch request to a local json file and I get this error saying Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0 pointing at response.json(). I tried adding proxy package.json but i get 500 internal error. How can I solve this?

componentDidMount() {    
  fetch('http://localhost:3000/items.json')
  .then(function(response) {
    if (response.status >= 400) {
      throw new Error("Bad response");
    }
    return response.json();
  })
  .then(function(data) {
    console.log(data)
  });
}

json file:

[
  {
    data: [
      {
        name: "cnt",
        level: "12"
      },
      {
        name: "stewart",
        level: "6"
      },
      {
        name: "nic",
        level: "7"
      }
    ]
  }
]
6
  • 1
    What is your backend part? Commented Aug 10, 2018 at 21:38
  • i'm using create react app. i'm doing the fetch within app.js Commented Aug 10, 2018 at 21:40
  • Which folder is your file located at? Commented Aug 10, 2018 at 21:45
  • 1
    If it's just create react app then there is no other backend running that can serve your JSON file. Consider importing it with Webpack instead. import obj from './items.json'. If you put the file in the public folder, you will be able to get it from the same origin: fetch('/items.json') Commented Aug 10, 2018 at 21:47
  • 1
    i tried both and then fetch('/items.json') worked in public folder. Commented Aug 10, 2018 at 21:52

2 Answers 2

3

If you are using Create React App then there is no other backend running that can serve your JSON file. Consider importing it with Webpack instead.

import data from './items.json';

class App extends React.Component {
  componentDidMount() {    
    console.log(data);
  }
  // ...
}

Alternatively, you could put the file in the public folder and you will be able to get it from the same origin.

class App extends React.Component {
  componentDidMount() {
    fetch("/items.json")
      .then(response => {
        if (!response.ok) {
          throw new Error("Bad response");
        }
        return response.json();
      })
      .then(data => console.log(data))
      .catch(error => console.error(error));
  }
  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

Put your file to public folder instead of src.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.