javascript - 当我使用 async/await 时,为什么会收到多个响应?

标签 javascript html rest asynchronous async-await

我正在为一个类编写一个简单的投票 Web API。我目前正在处理 PUT 并且我的代码正在运行,但我在命令行终端中遇到了一个奇怪的错误。这是我用来调用 PUT 的代码:

async addVotes(item) {
      try {
            let response = await axios.put("/api/candidates/" + item._id);
            this.getItems();
            return true;
          }
          catch (error) {
            console.log(error);
          }
          console.log(item.name + " is checked");
    },

async submitVotes(items) {
      for (var item of this.items) {
        if (item.selected) {

          this.addVotes(item);
        }
        else {
          console.log(item.name + " is not checked");
        }
      }
    },

这是 api 的 PUT 代码:

app.put('/api/candidates/:id', async(req, res) => {
  console.log("initiated put(edit) request");
  try {
    let candidate = await Candidate.findOne({ _id: req.params.id });
    candidate.numVotes += 1;
    candidate.save();
    res.send(candidate);
    res.sendStatus(200);
  }
  catch (error) {
    console.log(error);
    res.sendStatus(500);
  }
});

我收到一条错误消息:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
    at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
    at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
    at app.put (/var/www/html/MidRev/start.js:102:9)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
    at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
    at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
    at app.put (/var/www/html/MidRev/start.js:106:9)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:13246) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

根据我在线研究的内容,我收到此错误,因为我收到多个响应,但我正在使用 async/await,所以我不明白为什么我会收到该错误。

最佳答案

您向响应添加状态的方式不正确。

而不是

res.send(candidate);
res.sendStatus(200);

你应该这样做

res.status(200).send(candidate)

sendStatus 在设置状态代码的基础上发送“OK”消息。您可以引用此处的 Express API 引用 https://expressjs.com/en/api.html

关于javascript - 当我使用 async/await 时,为什么会收到多个响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58945852/

相关文章:

javascript - 如何获取(内置)麦克风的硬件信息?

azure - 从 Azure AD 对应用服务进行身份验证后如何获取用户和 token 详细信息?

javascript - 即时内容复制的文本输入框

javascript - jquery bootgrid 渲染最后一列重复中的​​值

php - 在 Woocommerce 3 中获取用户地理定位的国家名称

javascript - 自动垂直图像 slider

javascript - JQuery 选择器无法从外部 js 文件运行

rest - 使用 CORS 的跨域 REST/Jersey Web 服务

rest - 如何使用Apache Marathon REST API扩展Docker实例?

javascript - $scope 和 $rootscope 变量的生命周期