NodeJS-如果条件为真,则发送200次状态代码2次 [英] NodeJS - send 200 status code 2 times if condition is true

查看:251
本文介绍了NodeJS-如果条件为真,则发送200次状态代码2次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向客户端发送2次数据,但仅在某些条件为真时才向客户端发送第二个数据:例如,如果存在某个变量(在我的情况下,来自中间件req.userId,因为req.userId并非总是如此是从jwt令牌解码的id,因此如果令牌存在,则req.userId也存在.

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.

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

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

因此,如果我先写return res.status(200).send({data: JSON.stringify(data)}),它不会发送发送数据对象(都不是名称),但是当我进行身份验证并创建req.userId时,它会发送数据对象(不是名称),但是如果我第一次写条件,它不会发送首先发送任何内容,但是当我进行身份验证并创建req.userId时,它发送名称(不是数据对象),我真的很困惑,不知道为什么会这样

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

以下是我的反应代码:

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

自从我使用componentDidMount以来,它应该在页面内容加载时发送数据对象

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

谢谢!

推荐答案

对于单个请求,您无法两次答复.但是您可以管理不同答案的方式,例如:

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

这篇关于NodeJS-如果条件为真,则发送200次状态代码2次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆