簡體   English   中英

Express - NodeJS - 錯誤:將標題發送到客戶端后無法設置標題

[英]Express - NodeJS - Error: Cannot set headers after they are sent to the client

我有一個項目的問題。 我有一個外部 API,我需要調用它來獲取一些數據。 這個 API 呼叫分兩步進行。 首先,我向他們發送我的數據。 他們在 6-12 秒內計算出結果。 所以我添加了一個每秒執行一次的間隔,並向外部 API 詢問結果。

在請求結果之前,我發回了一個 400 狀態碼。 這樣前端應用就可以 go on 而不需要等待計算結果。

但是我總是收到錯誤消息,指出在將標頭發送給客戶端后我無法設置標頭。

我試圖刪除 catch 塊內的響應。 但這也無濟於事。 如果我從第二個 Axios 調用中刪除標頭,我會從外部服務器收到“未經授權”錯誤。

我還嘗試在 function 的開頭創建一個 axios 實例,並在那里設置標頭。 然后將該實例用於兩個調用。 但這里仍然存在錯誤。

(節點: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 at processTicksAndRejections (internal/process/task_queues.js:95:5) at async Timeout._onTimeout (/Users/stephen/Documents/projects/test-api/routes/blue.js:107:9)(使用node --trace-warnings...顯示警告的創建位置)(節點:37609)UnhandledPromiseRejectionWarning:未處理的 promise 拒絕。 此錯誤源於在沒有 catch 塊的情況下拋出異步 function,或者拒絕未使用 .catch() 處理的 promise。 要在未處理的 promise 拒絕時終止節點進程,請使用 CLI 標志--unhandled-rejections=strict (請參閱https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode )。 (拒絕 ID:2)(節點:37609)[DEP0018] DeprecationWarning:未處理的 promise 拒絕已棄用。 以后,未處理的 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,
    });
  });
});

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

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

如果您解決了axios.postaxios.get被拒絕,您將進入第二個res.status調用。

res.sendres.status不能作為return - function 繼續運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM