0

I have the following jquery's ajax call:

 const sendingData = {...}     

 $.ajax({
   url: "/api/data/getuser",
   type: "GET",
   data: sendingData ,
   dataType: 'json',
   ContentType: 'application/json',
   success: (data) => {
     console.log('SUCCESS')
     console.log(data)
     this.setState({
       isFetching: false,
       data: data.user
     })
   },  
   error: (err) => {
     console.log(err)
     this.setState({isFetching: false})
   } 
})

I'm tring to re-write it using fetch. I've tried this:

fetch("/api/data/getuser", {
  method: "GET",
  data: data,
  dataType: 'json',
  ContentType: 'application/json'
}).then((resp) => {
  console.log(resp)
}).catch((err) => {
  console.log(err)
})

The server should give me an object with user and other stuff, but all I get is this object:

Response {type: "basic", url: "http://localhost:3001/api/data/getuser", redirected: false, status: 200, ok: true, …}
body:ReadableStream
locked:(...)
__proto__:Object
bodyUsed:false
headers:Headers {}
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"http://localhost:3001/api/data/getuser"
__proto__:Response
}

2 Answers 2

4

You need to use resp.json() to get the response body as parsed JSON.

See https://developer.mozilla.org/en-US/docs/Web/API/Body/json

fetch("/api/data/getuser", {
  method: "GET",
  data: data,
  dataType: 'json',
  ContentType: 'application/json'
})
.then((resp) => {
  return resp.json();
})
.then((user) => {
  console.log(user);
})
.catch((err) => {
  console.log(err)
})
Sign up to request clarification or add additional context in comments.

Comments

1

Also you are missing headers.

fetch("/api/data/getuser", {
  data: data,
  headers: {
    'Content-Type': 'application/json'
  }
})
.then((resp) => {
  return resp.json();
})
.then((user) => {
  console.log(user);
})
.catch((err) => {
  console.log(err)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.