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
CodePudding user response:
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);
});
CodePudding user response:
Try this
fetch("http://localhost:4000/profile")
.then((response)=>{
response.json());
})
.catch(err=>{console.log(err)}).then((res)=> {console.log(res)})