在我的應用程式中,我有一個類別集合,用于保存類別標題及其影像 ID。影像與其元資料(如路徑、型別等)一起保存在另一個集合中。因此,為了檢索類別,我應該通過其 ID 檢索影像集合中的類別影像,并將影像路徑添加到從類別集合中檢索的類別物件并將其發送到客戶端......但我不知道應該將類別發送到客戶端的哪里?當我發送回應時遇到此錯誤:
throw er; // Unhandled 'error' event
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at ServerResponse.header (H:\node.js\online-store\app\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (H:\node.js\online-store\app\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (H:\node.js\online-store\app\node_modules\express\lib\response.js:267:15)
at ServerResponse.send (H:\node.js\online-store\app\node_modules\express\lib\response.js:158:21)
at H:\node.js\online-store\app\controllers\pcategory.controller.js:123:19
at H:\node.js\online-store\app\node_modules\mongoose\lib\model.js:4845:18
at processTicksAndRejections (internal/process/task_queues.js:77:11)
Emitted 'error' event on Function instance at:
at H:\node.js\online-store\app\node_modules\mongoose\lib\model.js:4847:15
at processTicksAndRejections (internal/process/task_queues.js:77:11) {
code: 'ERR_HTTP_HEADERS_SENT'
}
這是我的代碼:
exports.getAll = async (req, res) => {
try{
const categories = await ProductCategory.find({});
categories.map(async(category)=>{
await File.findById(category.imageID).exec(function(err,file){
if(err){
console.log(err)
}else if(file) {
category.imagePath = file.file_path;
tempCategories.push(category)
}
res.send(tempCategories);
})
})
return res.send(tempCategories);
}catch {
res.json(err =>{
console.log(err);
res.status(500).send({
message:
err.message || "There is an error in retrieving category"
});
})
}
}
uj5u.com熱心網友回復:
問題是您的代碼中沒有任何內容在等待您在map回呼中執行的異步操作完成,因此它會res.send在最后立即執行 - 然后在異步操作完成后稍后在回呼中res.send再次map執行。相反,等待他們完成并發送結果。
此外,您正在使用res.send我懷疑您想要的地方res.json,并且res.json稍后使用不正確(它不需要回呼)。
看評論:
exports.getAll = async (req, res) => {
try {
// Get the categories
const categories = await ProductCategory.find({});
// Get the files for the categories, wait for the result
const result = await Promise.all(categories.map(async (category) => {
const file = await File.findById(category.imageID).exec();
// You probably can't modify the `category` object, so let's create
// and return a new object
return {...category, imagePath: file.file_path};
}));
// Send the result converted to JSON
return res.json(tempCategories);
} catch (err) { // Accept the error
// Send an error response
res.status(500).json({
message: err.message || "There is an error in retrieving category"
});
}
};
旁注:您的原始代碼map沒有使用它創建的陣列。這是一種反模式(可悲的是,它似乎是某個地方的某個人正在教學)。我在這里寫了為什么和做什么。(在我對您的代碼的更新中,我仍然使用map,但我使用它創建的陣列,將其傳遞給Promise.all以便我們可以等待所有這些承諾得到解決。)
uj5u.com熱心網友回復:
您收到此錯誤是因為您撥打了res.send()兩次電話。沒有必要這樣做,除非您回傳的內容在兩次呼叫 pr 之間發生了一些變化,因為第一次呼叫需要滿足一個條件。如果您必須呼叫res.send()兩次,請確保添加return到第一個呼叫中,因此它變為:
return res.send(data);
這樣,第二個呼叫不會被執行,因為函式在這一行之后立即退出。一個例子如下所示:
if (someConditionIsMet()) {
return res.send(data); // Function exits after this
}
res.send(differentData);
但是,在您的情況下,您正在呼叫res.send()地圖功能,這不是您想要的。您所需要的只是return在地圖功能中執行所需的操作之后。像這樣:
exports.getAll = async (req, res) => {
try {
const categories = await ProductCategory.find({});
categories.map(async (category) => {
await File.findById(category.imageID).exec(function(err, file) {
if (err) {
console.log(err);
} else if (file) {
category.imagePath = file.file_path;
tempCategories.push(category);
}
});
return tempCategories; // Simply return the data here, not res.send()
});
res.send(tempCategories); // Send the data back to the client here
} catch (err) {
console.log(err);
res.status(500).send({
message: err.message || "There is an error in retrieving category"
});
}
}
uj5u.com熱心網友回復:
你的代碼像這樣,
現在的問題是您發送了兩次標題。
您可以像這樣使用,首先宣告陣列并將您需要的內容推入其中,然后最后的邏輯回傳或發送它。
exports.getAll = async (req, res) => {
try {
const categories = await ProductCategory.find({});
let tempCategories = []; // New Line
await Promise.all(categories.map(async (category) => {
await File.findById(category.imageID).exec(function (err, file) {
if (err) {
console.log(err)
} else if (file) {
category.imagePath = file.file_path;
tempCategories.push(category)
}
});
return category;
}));
res.send(tempCategories);
} catch {
res.json(err => {
console.log(err);
res.status(500).send({
message:
err.message || "There is an error in retrieving category"
});
})
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326702.html
標籤:javascript 节点.js 表达 猫鼬
下一篇:我可以實作進入參考嗎
