NodeJS - send 200 status code 2 times if condition

2019-08-26 15:41发布

问题:

I to send data 2 times to client but only send second data to client if some condition is true for example: if some variable exists (from middleware, in my case: req.userId which is not always expected since req.userId is decoded id from jwt token so if token exists, req.userId exists too.

I am validating user in that way, if user has authenticated s/he has token and I send additional data, otherwise I should send data that is visible for everyone) send header to client with 200 status code (I mean that header is not for error) and continue code execution and outside of that if statement there is second header to send also with 200 status code, but if condition is false skip that condition and just send second header which is sent in every case, and client side (react js) check if that data exists and then set it to state or do whatever to prevent undefined variables, client side validation is easy I already did it but because of my buggy code I got undefined.

Anyway, I knew it and it was planned that i would get undefined without checking, so problem is not in client side, it's in server side and here's problem: my code only sends header which is first in code here is my code

router.get("/", async (req, res) => {
  var data = { foo: "bar", foo1: "bar1" };

  if (req.userId) {
    const user = await User.findById({ _id: req.userId }, "-password").lean();

    res.status(200).send({ name: user.username });
  }

  return res.status(200).send({ data: JSON.stringify(data) });
});

So if I write return res.status(200).send({data: JSON.stringify(data)}) first it does not send send data object (neither not name) but when i authenticate and create req.userId it sends data object (not name), but if i first write condition it does not sends anything at first but when i authenticate and create req.userId it sends name (not data object), i am really confused and don't know why is this happening

Here is my react code if it matters:

componentDidMount() {
  axios
    .get("/api/main")
    .then(res => res.data)
    .then(data => {
      this.setState({ name: data.name });

      alert(data.data);
    })
    .catch(error => {
      if (error.response) {
        console.log(error.response.data.message);
      }
    });
}

Since I am using componentDidMount it should send data object when page content loads

THANKS!

回答1:

You can't reply twice for a single request. But you can manage the way you answer differently, for example :

router.get("/", async (req, res) => {
  var data = { foo: "bar", foo1: "bar1" };

  if (req.userId) {
    const user = await User.findById({ _id: req.userId }, "-password").lean();

    data.name = user.username;
  }

  return res.status(200).send({ data: JSON.stringify(data) });
});