我尝试通过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);”时完成后,它会在 axios.post ... catch(error)部分显示警告。
有人有好主意应对吗?
谢谢。
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.
});
答案 0 :(得分:0)
这是服务器端错误,原因是服务器无法重写已发送给客户端的响应的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的基本行为,即服务器已经发送响应后就无法将数据发送到客户端。所以这不是一个明确的问题,这是HTTP的限制。如果您希望服务器能够将数据“推送”到客户端,则必须使用websockets。