user14704144
user14704144

Reputation:

Express response.send() object not received by JavaScript fetch() ... why?

Documentation from Express response.send allows for objects to be sent in the body, which I am sending as follows:

  DBM.saveArticle(obj).then((val) => {
    console.log(val); // verified here
    res.send(val);
    res.end();
    // ... clip here

However on the client I am not getting the object. This is a Create in CRUD, and I am using fetch POST as follows to implement this.

    // ... snip
    const options = { 
      headers: {'Content-Type': 'application/json'}, 
      method: 'POST', 
      body: JSON.stringify(this.state)
    };    
    fetch("/articles/add", options)
      .then((response) => {
        console.log('DEBUG: Article Added: ', response); // nothing found here in response
        this.props.dispatch({type: 'addArticle', component_state: state});
      })
      .catch((error) => {
        console.log('fetch/POST error', error);
      });
      // ... snip

console.log from above looks like this, here is a pic, it is empty, as far as I can tell.

enter image description here

The response object is big, and I tried to click all about it, but it is possible I might have missed something.

The official docs for JavaScript fetch response object is here on MDN.

Upvotes: 0

Views: 79

Answers (1)

Rami Jarrar
Rami Jarrar

Reputation: 4643

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Response_objects

This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method (defined on the Body mixin, which is implemented by both the Request and Response objects.)

https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream

The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.

fetch returns the body as a ReadableStream to convert it to a JSON use response.json()

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())   // << this will convert the response to JSON object
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

The data in the ReadableStream is not accessible without consuming the stream, it's stored in a lower-level I/O source, called the underlying source, and there are two types of underlying source: push and pull sources.

In case of HTTP request it's a push source in the form of a TCP socket, where data is constantly being pushed from the OS level, and the data will be accessible to the consumer (your code) once you acquire a lock and start reading it, which is exactly what json() method do for you.

refer to this for more details https://streams.spec.whatwg.org/#rs-model

Upvotes: 1

Related Questions