Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the data from fetch -> promise -> response

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.

like image 936
Zoli Avatar asked Jul 14 '16 15:07

Zoli


People also ask

What does the promise returned by fetch () resolve to?

Using Fetch Calling fetch() returns a promise. We can then wait for the promise to resolve by passing a handler with the then() method of the promise. That handler receives the return value of the fetch promise, a Response object.

What is a fetch promise?

A fetch() promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A fetch() promise does not reject on HTTP errors ( 404 , etc.). Instead, a then() handler must check the Response. ok and/or Response.

How do you read a fetch body?

To read the body of a Fetch promise with JavaScript, we can use the json method. const f = async () => { const response = await fetch("https://api.ipify.org?format=json"); const data = await response. json(); console. log(data); };


1 Answers

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.

like image 88
KevBot Avatar answered Sep 19 '22 06:09

KevBot