Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node/Express - res.status().send() only sends the status but does not send an object

I am having an issue with a route in my backend where res.status().send() will only send the client the status code, but it will not send the client the object located inside of send().

Here is my code (redacted all code but the problem for brevity):

exports.user_signup = (req, res) => {
  const { body } = req;
  const { companyName, password, email } = body;

  User.find({ email: email }, (err, previousUsers) => {
    if (err) {
      return res.status(400).send({
        message: "There was an issue signing up."
      });
    } else if (previousUsers.length > 0) {
      return res.status(403).send({
        message: "Records show this email is linked to another account."
      });
    }
}

When I make my fetch request from the client, the response only returns the status code from the server, but nowhere in the response is the object in the send() method on the server. Just spitballing, I threw res.status(200).json(object) at it to send the object as json to no avail.

Here is my `fetch request from the client:

  fetch("http://localhost:3000/users/accounts/", {
    method: "post",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(userData)
  }).then(response => console.log(response));
}

To show what response I am getting, I purposely posted some form data from the client to the route that would throw the 403 error, and this is the response I get in the browser console:

Response {type: "basic", url: "http://localhost:3000/users/accounts/", redirected: false, status: 403, ok: false, …}

So I am able to successfully send the status back from the route to the client, however I can not for the life of me figure out why send() does not send the object along with it.

like image 934
maison.m Avatar asked Oct 18 '25 09:10

maison.m


1 Answers

The body of the response that comes back from fetch() is a ReadableStream. You need to process it to turn it into something usable. Normally you would call response.json() to parse it as a JSON object:

fetch("http://localhost:3000/users/accounts/", {
    method: "post",
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify(userData)
})
    .then(response => response.json())
    .then(response => console.log(response));
}
like image 187
Jim B. Avatar answered Oct 19 '25 23:10

Jim B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!