Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to access response data using fetch

I'm trying something simple where I make a request from the front end of my app using the fetch API like so

let request = new Request('http://localhost:3000/add', {
    headers: new Headers({
        'Content-Type': 'text/json' 
    }),
    method: 'GET'
});

fetch(request).then((response) => {
    console.log(response);
});

I am handling this request on the server like so,

app.get('/add', (req, res) => {
    const data = {
        "number1": "2", 
        "number2": "4"
    };
    res.send(data);
});

However, when I try to access my data on the front end console.log(response), I get the following object

Response {type: "basic", url: "http://localhost:3000/add", redirected: false, status: 200, ok: true…}
body:(...)
bodyUsed:false
headers:Headers
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"http://localhost:3000/add"
__proto__:Response

The response body is empty. I assumed that's where the data would show up? How do I pass data effectively from the server?

like image 592
random_coder_101 Avatar asked Jul 28 '17 06:07

random_coder_101


People also ask

How do I access data from fetch response?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

How do I get json from fetch response?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON 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

Okay, this works on my front end

fetch(request).then((response) => {
    console.log(response);
    response.json().then((data) => {
        console.log(data);
    });
});

The key part was the resolution of the promise chain.

Similar question here JavaScript fetch API - Why does response.json() return a promise object (instead of JSON)?

like image 59
random_coder_101 Avatar answered Sep 21 '22 14:09

random_coder_101