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

标签 javascript node.js express fetch

我的后端路由有问题,其中 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."
      });
    }
}

当我从客户端发出我的获取请求时,响应只从服务器返回状态代码,但响应中没有任何地方是中的对象>send() 服务器上的方法。只是随地吐痰,我向它扔了 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));
}

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

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

所以我能够成功地将状态从路由发送回客户端,但是我终究无法弄清楚为什么 send() 没有将对象与其一起发送.

最佳答案

fetch() 返回的响应的 body 是一个 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));
}

关于javascript - Node/Express - res.status().send() 只发送状态但不发送对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53551851/

相关文章:

javascript - 主干路由——检测浏览器后退按钮按下

node.js - 使用 node.js 运行数据库迁移 (mongodb)

node.js - 给定图像的本地相对 url,如何获取要发送的实际图像

JavaScript 将参数传递给模态 ASP.NET Core

javascript - 使用 jQuery Ajax 将数据从 MySQL 加载到 JavaScript Array of Array

linux - 让 meteor 0.9.2 构建工作 OSX -> Linux

javascript - 来自远程 API 的 Set-Cookie 不起作用

javascript - Angular $http.get 不传递参数

javascript - codeigniter 尝试使用 javascript 从 View 访问 session 数据

node.js - 在 Linux 上从二进制文件安装 Node 需要哪些 tar 选项?