0

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");});
 }   
3
  • 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. Commented May 30, 2018 at 9:22
  • 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? Commented May 30, 2018 at 9:27
  • I changed the location of json file into public folder in react application and it works fine! Commented May 30, 2018 at 10:13

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.