Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch response.json() and response.status

Is this the only way to use the body.json() and also get the status code?

let status;  return fetch(url)     .then((response => {          status = response.status;          return response.json()      })     .then(response => {         return {             response: response,             status: status         }     }); 

This doesn't work as it returns a promise in the response field:

.then((response)=> {return {response: response.json(), status: response.status}}) 
like image 671
Guy Avatar asked Nov 13 '17 14:11

Guy


People also ask

What does Response JSON () do in Fetch?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

How do I get response status code on Fetch?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.

Does fetch return a JSON?

The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and does not directly return the JSON response body but instead returns a promise that resolves with a Response object.

What is response in Fetch?

The Response interface of the Fetch API represents the response to a request. You can create a new Response object using the Response() constructor, but you are more likely to encounter a Response object being returned as the result of another API operation—for example, a service worker FetchEvent.


1 Answers

Your status is not visible in the second then. You can just get the two properties in the single then.

json() returns a new Promise to you, so you need to create your object inside the then of the result of that function. If you return a Promise from a function, it will be fulfilled and will return the result of the fulfillment - in our case the object.

fetch("https://jsonplaceholder.typicode.com/posts/1")  .then(r =>  r.json().then(data => ({status: r.status, body: data})))  .then(obj => console.log(obj));
like image 155
Suren Srapyan Avatar answered Sep 21 '22 09:09

Suren Srapyan