Home > OS >  Express res.send or res.json doesn't contain a body
Express res.send or res.json doesn't contain a body

Time:11-23

I'm calling an API to fetch orders for a given user based on ID which are fetched from a third-party site. These are fetched correctly as a console.log them in the node server. But when I try to send the results back to the client neither res.send nor res.json results sending the data back to the client. Here is an example of an order from console.log:

{"customer":{"orders":{"edges":[{"node":{"id":"gid://shopify/Order/1234564564","lineItems":{"edges":[{"node":{"title":"Some title here"}}]}}}]}}}

Then on the client in the devtools when I console.log the response I get:

body:ReadableStream
  locked:false
  [[Prototype]]:ReadableStream
bodyUsed:false
headers: 
   Headers {}
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"http://localhost:9000/api/getOrders?cid=gid://shopify/Customer/1234564564"
[[Prototype]]:Response

Any help is appreciated.

=== UPDATE ===

I've now even tried the most basic of examples and am getting the same response on the client:

app.get('/testExpress', (req, res) => {
  res.send("Hello")
});

Thanks to @laurent here is how I was able to receive that response on the client:

fetch('/testExpress')
  .then(async (r) => {
    const resp = await r.text();
    console.log(resp);
  })

CodePudding user response:

You should try to get the json out of the response by const json = await response.json().

These are the available methods to parse the response body depending on what you want:

Response.arrayBuffer() Returns a promise that resolves with an ArrayBuffer representation of the response body.

Response.blob() Returns a promise that resolves with a Blob representation of the response body.

Response.clone() Creates a clone of a Response object.

Response.formData() Returns a promise that resolves with a FormData representation of the response body.

Response.json() Returns a promise that resolves with the result of parsing the response body text as JSON.

Response.text() Returns a promise that resolves with a text representation of the response body.

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

The Response object is a representation of the http response. You should try to receive the body of the response by using one of these methods or parsing the body from the readable stream response.body.

  • Related