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

mai*_*n.m 2 javascript fetch node.js express

我的后端路由存在问题,该路由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."
      });
    }
}
Run Code Online (Sandbox Code Playgroud)

当我fetch request从客户端创建时,响应只status code从服务器返回,但响应中没有任何地方是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));
}
Run Code Online (Sandbox Code Playgroud)

为了显示我得到的响应,我特意将一些表单数据从客户端发布到会引发 403 错误的路由,这是我在浏览器控制台中得到的响应:

Response {type: "basic", url: "http://localhost:3000/users/accounts/", redirected: false, status: 403, ok: false, …}
Run Code Online (Sandbox Code Playgroud)

所以我能够成功地将状态从路由发送回客户端,但是我一生都无法弄清楚为什么send()不将对象与它一起发送。

Jim*_* B. 5

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));
}
Run Code Online (Sandbox Code Playgroud)

  • Boom 是我最喜欢的反应。 (2认同)