Unable to get data from express to react

Issue

I am trying to fetch data from express to react using fetch api. Both are being run on localhost.
Here’s my backend code :

 app.get("/profile",(req,res)=>{
   const data = [{
     name:"shekhar",
     class:"5"
   }]
   res.send(JSON.stringify(data));
 });

 React code:
 
 function handleSubmit(){
   fetch("http://localhost:4000/profile")
   .then((response)=>{
     console.log((response));
   })
   .catch(err=>{console.log(err)})
 }
 
 handleSubmit();
 function handleSubmit(){
   fetch("http://localhost:4000/profile")
   .then((response)=>{
     console.log((response));
   })
   .catch(err=>{console.log(err)})
 }
 
 handleSubmit();
 
 The result it is showing in react console:
 Response {type: 'cors', url: 'http://localhost:4000/profile', redirected: false, status: 200, ok: true, …}


But its not showing the express object. but it is showing a response object. I have tried several answers over here but I couldn’t resolve the issue. Kindly help me what to do I am new to this. ty

Solution

It will return an promise not an actual data, to get an actual data you need to resolve promise like this

fetch("http://localhost:4000/profile")
.then(response => response.json())
.then(data => {
 console.log(data);
});

Answered By – Guest

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published