Home > Net >  How to Fetch from my local host? Connect React.js to Node.js
How to Fetch from my local host? Connect React.js to Node.js

Time:02-05

Creating my first MERN application and connected the frontend to the backend.

Taking baby steps and trying to simply call the already existing "books" in my mongo database.

Heres what I have

 const fetchingFunction = () => {

   fetch('http://localhost:5000/books', {
     method: "GET",
     headers: {
       "Content-Type": "application/json",
       'Accept': 'application/json'
     }
   }).then(function(response) {

      response.json();

   }).then(data => console.log(data))

 }

I keep getting the error


Uncaught (in promise) SyntaxError: Unexpected token h in JSON at position 0

CodePudding user response:

You need to return the response.json().

 const fetchingFunction = () => {

   fetch('http://localhost:5000/books', {
     method: "GET",
     headers: {
       "Content-Type": "application/json",
       'Accept': 'application/json'
     }
   }).then(function(response) {

      return response.json();

   }).then(data => console.log(data))

 }

CodePudding user response:

adding response.json() will solve your problem

  •  Tags:  
  • Related