UnhandledPromiseRejectionWarning: Ошибка [ERR_HTTP_HEADERS_SENT] - setInterval & Ax ios .post обработка ошибок - PullRequest
1 голос
/ 19 апреля 2020

Я пытался обработать это предупреждение с помощью Google. Однако, так как я не смог решить это предупреждение, я задаю этот вопрос.

Теперь я вижу следующее предупреждение:

(node:39452) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:485:11)
    at ServerResponse.header 
...
    at ServerResponse.send 
...
    at ServerResponse.json 
...
    at ServerResponse.send 
...
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async Timeout.priceAlarm [as _onTimeout] 
(node:39452) 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: 3)

Когда вызывается "priceAlarm", это нормально. Однако когда "intervalPriceAlarm = setInterval (priceAlarm, 3000, res, chatId);" сделано, это показывает предупреждение в ax ios .post ... catch (error) part.

У кого-нибудь есть хорошая идея справиться с этим?

Спасибо.

function priceAlarm(res, chatId) {
                axios
                  .get(url)
                  .then((response) => {
                    currentBtcBitfinexUsd = getPrice(
                      response.data.tickers,
                      "BTC",
                      "USD",
                      "bitfinex"
                    );

                    axios
                      .post( `${telegramBotUrl}${apiToken}/sendMessage`, {
                        chat_id: chatId,
                        text:
                          "\nBitfinex- BTC(USD):" +
                          currentBtcBitfinexUsd,
                      })
                      .then((response) => {
                        res.status(200).send(response);
                      })
                      .catch((error) => {
                        res.send(error); //****this part shows an error!*****
                      });

                  })
                  .catch((error) => {
                    console.log(error);
                  });
} 
function intervalAlarm(res,chatId){
  if (alarmFlag == 1 && intervalPriceAlarm == null) {
    intervalPriceAlarm = setInterval(priceAlarm, 3000, res, chatId);
    console.log(intervalPriceAlarm); //need to remove it
  }else{
    console.log("doing nothing");
  }
}
app.post("/", (req,res) =>{ 
     const chatId = req.body.message.chat.id;
     const sentMessage = req.body.message.text;

     if (sentMessage.match(/price/gi)) {
       priceAlarm(res, chatId); //No problem at all
     } else if (sentMessage.match(/start/gi)) {
       alarmFlag=1;       
       res.status(200).send({});
     } else if(sentMessage.match(/stop/gi)){
       alarmFlag=0;
       res.status(200).send({});
     } else {
       res.status(200).send({});
     }
    intervalAlarm(res,chatId);  // here setInterval part.
});

1 Ответ

0 голосов
/ 19 апреля 2020

Это ошибка на стороне сервера из-за того, что сервер не может перезаписать заголовки HTTP ответа, который он уже отправил клиенту. Следовательно, вы не можете res.send() дважды повторять res, но вы делаете это в своем коде

// here the first time
priceAlarm(res, chatId); //No problem at all

// here the second time
intervalAlarm(res,chatId);  // here setInterval part.

Вам придется переписать свой код, потому что это базовое поведение HTTP, что сервер не может отправить данные клиенту уже после отправки ответа. Так что это не проблема express, это ограничение HTTP. Если вы хотите, чтобы ваш сервер мог отправлять данные на ваш клиент, вы должны вместо этого использовать веб-сокеты.

...