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

3
我在我的后端路由中遇到了一个问题,当使用 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请求时,响应只返回服务器的状态码,但响应中没有send()方法中的对象。我试着将res.status(200).json(object)发送给它,以将对象作为json发送,但没有成功。

这是我从客户端发起的 `fetch请求:

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

为了展示我所获得的响应,我故意向客户端发送一些表单数据到会抛出403错误的路由,以下是我在浏览器控制台中收到的响应:
Response {type: "basic", url: "http://localhost:3000/users/accounts/", redirected: false, status: 403, ok: false}

我可以成功地将状态从路由发送回客户端,但是我无法理解为什么send()不会将对象一起发送。

1个回答

8

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

太棒了,这正是我想要的。感谢您快速而深入的回复。 - maison.m
7
Boom是我最喜欢的反应。 - Jim B.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接