简体   繁体   English

NodeJS-如果条件为真,则两次发送200状态代码

[英]NodeJS - send 200 status code 2 times if condition is true

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. 我向客户端发送数据两次,但仅在某些条件为真时才向客户端发送第二个数据,例如:如果存在某个变量(在我的情况下,来自中间件:req.userId,由于req.userId解码为id,因此并不总是期望的来自jwt令牌,因此如果令牌存在,则req.userId也存在。

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. 我以这种方式验证用户,如果用户已通过身份验证,则他/她具有令牌并且我发送了其他数据,否则我应该发送所有人都可见的数据)将标头发送给带有200状态代码的客户端(我的意思是标头不适用于错误)并继续执行代码,在if语句之外,还有第二个标头也要发送200个状态代码,但是如果条件为false,则跳过该条件,仅发送在每种情况下发送的第二个标头,并发送客户端(响应js )检查数据是否存在,然后将其设置为state或采取任何措施来防止未定义的变量,客户端验证很容易,我已经做到了,但是由于我的错误代码使我无法定义。

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 因此,如果我编写return res.status(200).send({data: JSON.stringify(data)})则它首先不发送发送数据对象(也不是名称),但是当我进行身份验证并创建req.userId时,它将发送数据对象(不是名称),但是如果我第一次写入条件,它最初不会发送任何信息,但是当我进行身份验证并创建req.userId时,它发送名称(不是数据对象),我真的很困惑,不知道为什么会这样

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 由于我正在使用componentDidMount,因此当页面内容加载时,它应该发送数据对象

THANKS! 谢谢!

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) });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM