Shekhar lohach
Shekhar lohach

Reputation: 85

Unable to get data from express to react

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

Upvotes: 0

Views: 1003

Answers (2)

Farhad Faraji
Farhad Faraji

Reputation: 147

Try this

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

Upvotes: 1

Guest
Guest

Reputation: 46

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);
});

Upvotes: 2

Related Questions