21

I am trying to post some data to the server but I don't know how to get back the response data.

I have the following code:

fetch(url, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    email: login,
    password: password,
  })
}).then(function(a){
  console.log(a);
})

It prints a Response it contains data such as body (ReadableByteStream), bodyUsed (false), ok (true), status (200),... but I cannot find the data I get back, nowhere. When I open the chrome developer console - network I see the response data there.

What am I doing wrong?

I've been looking for some resources how fetch, promises,... work but I couldn't find any well written.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Zoli
  • 831
  • 1
  • 11
  • 27

2 Answers2

35

There are further methods you call on a fetch response, such as .json(), or .blob(). These methods return a promise which you can call .then() on.

fetch(url, {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        email: login,
        password: password,
    })
})
    .then(function (a) {
        return a.json(); // call the json method on the response to get JSON
    })
    .then(function (json) {
        console.log(json)
    })

Check out some documentation on using fetch, and some other documentation on how the response object works in a fetch call.

KevBot
  • 17,900
  • 5
  • 50
  • 68
0

fetch returns Promise which could be resolved to Response object that has several methods, like text(), json(), blob(), which also return Promise with String / Object / Blob.

So you have to resolve promises twice!!

fetch(...)
    .then((rsp) => rsp.json())
    .then((obj) => console.log(obj));
gavenkoa
  • 45,285
  • 19
  • 251
  • 303