0
votes

I'm a beginner in using fetch API, I'm trying to fetch json data within react application but it keeps returning 500 (Internal Server Error) The react application is running under http://localhost:3000/

I'v already added proxy in package.json file:

"proxy": "http://localhost:3000"

Below is a sample json file data/greeting.json:

{
  "time": "am",
  "greeting": "Good morning"
}

caller.js file has a method to call json:

function getGreetings() {
    fetch(`./data/greeting.json`, {
        headers : {
          "Content-Type": "application/json",
          "Accept": "application/json"
        }
    })
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
 }   
2
It looks you are trying to load a file with fetch. You should reach an endpoint where you read the file whose content you want to retrieve. - Dez
yes I'm trying to get the data in json file, but I didn't get what you mean by reading the file, do you think there is something missing with my code? - user1477701
I changed the location of json file into public folder in react application and it works fine! - user1477701

2 Answers

2
votes

Since the JSON file also resides inside your directory, instead of using fetch for getting the data, you can just directly input the file content as trivial require.

In your context, you can do something like this:

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

I hope this small code fragment will help.

Cheers!

0
votes

Try removing the dot in your url (and possibly, the slash). If that's not it, then I'm guessing that there's something wrong with your server code.