【问题标题】:Express - NodeJS - Error: Cannot set headers after they are sent to the clientExpress - NodeJS - 错误:在将标头发送到客户端后无法设置标头
【发布时间】:2021-10-24 11:07:35
【问题描述】:

我的项目有问题。我有一个外部 API,我需要调用它才能获取一些数据。此 API 调用分两步进行。首先,我向他们发送我的数据。他们在 6-12 秒内计算出结果。所以我添加了一个间隔,它每秒执行一次,并向外部 API 询问结果。

我在询问结果之前发回了 400 状态码。这样前端应用就可以继续运行,不需要等待计算结果。

但我总是收到一条错误消息,指出在将标头发送到客户端后我无法设置它们。

我试图删除 catch 块内的响应。但这也无济于事。如果我从第二个 Axios 调用中删除标头,我会从外部服务器收到“未经授权”错误。

我还尝试在函数的开头创建一个 axios 实例并在那里设置标题。然后将该实例用于两个调用。但是这里的错误仍然存​​在。

(node:37609) UnhandledPromiseRejectionWarning: 错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头 在 ServerResponse.setHeader (_http_outgoing.js:561:11) 在 ServerResponse.header (/Users/stephen/Documents/projects/test-api/node_modules/express/lib/response.js:771:10) 在 ServerResponse.send (/Users/stephen/Documents/projects/test-api/node_modules/express/lib/response.js:170:12) 在 ServerResponse.json (/Users/stephen/Documents/projects/test-api/node_modules/express/lib/response.js:267:15) 在 /Users/stephen/Documents/projects/test-api/routes/blue.js:143:45 在 processTicksAndRejections (internal/process/task_queues.js:95:5) 在异步 Timeout._onTimeout (/Users/stephen/Documents/projects/test-api/routes/blue.js:107:9) (使用node --trace-warnings ... 显示警告的创建位置) (节点:37609)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 CLI 标志 --unhandled-rejections=strict(请参阅 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝编号:2) (节点:37609)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

router.post('/calculate/:plotId', verify, async (req, res) => {
  const info = req.body;

  const auth = `Basic ${Buffer.from(`${process.env.USERNAME}:${process.env.PASSWORD}`).toString('base64')}`;

  const headers = {
    Authorization: auth,
    'Content-Type': 'text/plain; charset=utf-8',
    Host: 'test.app.be',
  };

  await axios.post('https://test.app.be/label', info, {
    headers,
  }).then(async (response) => {
    res.status(201).json({
      message: 'blue label sended!',
    });

    async function getResult(key) {
      const interval = setInterval(async () => {
        await axios.get(`https://test.app.be/result/${key}`, {
          headers,
        }).then(async (resp) => {
          // Calculating Blue score failed
          if (resp.data.status && resp.data.status === 'failed') {
            clearInterval(interval);
          }

          const data = resp.data.ontwerp;

          if (!data) return;

          clearInterval(interval);
        }).catch((error) => {
          res.status(400).json({
            message: error,
          });

          clearInterval(interval);
        });
      }, 1000);
    }

    getResult(response.data[0].result_id);
  }).catch((error) => {
    res.status(400).json({
      error,
    });
  });
});

【问题讨论】:

  • 你发送 res.json 两次,“蓝色标签发送!”和“消息:错误”。
  • @KapilSharma 感谢您的快速回答。我已经尝试过了。但是当我删除第二个 res.status 时,错误仍然存​​在。

标签: javascript node.js express axios http-headers


【解决方案1】:

axios.post....res.status(201) - 第一个res.status

async function getResult(key) ... axios.get...catch(...res.status(400)) - 秒

如果您解决了axios.post 并拒绝了axios.get,您将转入第二个res.status 呼叫。

res.send 或 res.status 不能像 return 那样工作 - 函数继续运行。

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 2019-12-25
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多