代码之家  ›  专栏  ›  技术社区  ›  maison.m

Node/Express-res.status().send()只发送状态,不发送对象

  •  0
  • maison.m  · 技术社区  · 6 年前

    res.status().send() 将只向客户端发送状态代码,但不会向客户端发送位于 send() .

    这是我的代码(为简洁起见,编辑了所有代码,但问题是):

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

    当我做出决定的时候 fetch request 从客户端,响应只返回 status code 来自服务器,但响应中没有响应中的对象 发送() 方法。我只是随地吐痰 res.status(200).json(object) json

    这是我从客户端发出的“获取”请求:

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

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

    因此,我能够成功地将状态从路由发送回客户机,但我始终无法找出原因 发送() 不随对象一起发送。

    1 回复  |  直到 6 年前
        1
  •  5
  •   Jim B.    6 年前

    这个 body 从中得到的反应 fetch() ReadableStream . 你需要处理它,把它变成有用的东西。通常你会打电话 response.json() 要将其解析为JSON对象,请执行以下操作:

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