[ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头(也与promise问题有关)


//get the trending rates
exports.getTrendingRates = async (req, res) => {
let comArr = [];
await quoteModel.find({}).then((result) => {
for (let i = 0; i < result.length; i++) {
comArr.push({
PL: result[i].PL,
PD: result[i].PD,
CS: result[i].CS,
CT: result[i].CT,
});
}
let finalRes = comArr.reduce(function (acc, curr) {
let isElemExist = acc.findIndex(function (item) {
return (
item.PL === curr.PL &&
item.PD === curr.PD &&
item.CS === curr.CS &&
item.CT === curr.CT
);
});
if (isElemExist === -1) {
let obj = {};
obj.PL = curr.PL;
obj.PD = curr.PD;
obj.CS = curr.CS;
obj.CT = curr.CT;
obj.count = 1;
acc.push(obj);
} else {
acc[isElemExist].count += 1;
}
return acc;
}, []);
//getting the most search most quotes
let sortedData = finalRes.sort((a, b) => b.count - a.count);
let returnObj = {
id: req.params.id,
sortedData,
};
//filter function to searched user most search quotes in rates collections
sortedData.forEach(async (value) => {
const filter = {
$and: [
{ PL: { $regex: value.PL, $options: "i" } },
{ PD: { $regex: value.PD, $options: "i" } },
{ CS: { $regex: value.CS, $options: "i" } },
{ CT: { $eq: value.CT } },
],
};
await ratesModel
.find(filter)
.then((result) => {
console.log(result);
return res.status(200).send({ result });
})
.catch((err) => console.log(err));
});
});
};

**我不知道为什么我会出现这个错误,即使我没有使用多个响应。请大家检查一下这个代码,帮我一下。我到处检查过,但都有错误的期望。通常情况下,这个错误通常是通过使用多个响应而发生的。**

此错误的原因是试图向同一传入请求发送多个响应。而且,你正是这么做的。

此代码:

await ratesModel.find(filter).then(result => {
console.log(result)
return res.status(200).send({result})
})

sortedData.forEach()循环中,因此只要数组中有多个项,就会多次调用res.status(200).send({result}),从而生成错误。

我不知道你想在这个特定的代码中发送什么结果,但通常的解决方案是在循环中累积结果,然后在循环后发送最后一个累积结果。

仅供参考,您的await xxxx.find().then().catch()模式使您的代码更难阅读、编写和调试。请始终使用await.then(),而不是在同一语句或函数中同时使用两者。它们是一种解决相同基本问题的编码样式,因此您应该决定在函数中使用哪种编码样式并保持一致。

最新更新