我有一個將回傳回應的函式,res.send()但在呼叫該函式之后,以下代碼行將一直執行。
const db = require('../models');
exports.findAll = (req, res) => {
checkAuthorization(req, res, 'Customer');
db.User.findAll({ include: ['created', 'restaurant'] })
.then((data) => {
res.send({
error: false,
data: data,
message: ['Retrieved successfully.'],
});
})
.catch((err) => {
console.log(err);
res.status(500).send({
error: true,
data: [],
message: err.errors.map((e) => e.message),
});
});
};
這是checkAuthorization功能
const checkAuthorization = (req, res, user_type) => {
// Check if user_type param is null
if (user_type == null) return res.status(500).send('`user_type` parameter is required');
// Check if user_type param has valid value
const validuser_type = user_type === 'Customer' || user_type === 'Resto_Admin' || user_type === 'Admin';
// Validate user_type parameter
if (!validuser_type) return res.status(500).send('The value for `user_type` parameter is invalid');
// Check if user is not authorized
if (!(req.user != null && req.user.user_type === user_type))
return res.status(401).send('Oops! You are unauthorized to view your request');
};
這是我得到的錯誤。
錯誤 [ERR_HTTP_HEADERS_SENT]:在將標頭發送到客戶端后無法設定標頭
uj5u.com熱心網友回復:
“從函式回傳”和“從 Web 服務器向用戶回傳回應”是兩個非常不同的東西。該checkAuthorization函式正在發送回應,但沒有向呼叫函式表明它已經這樣做了。所以呼叫函式也嘗試發送回應。
不要“回傳”對res.statusfrom的呼叫checkAuthorization。如果它需要發送回應,它可以這樣做,但也應該從函式回傳一些指示它這樣做了。像布林值這樣簡單的東西可以作業。例如:
const checkAuthorization = (req, res, user_type) => {
// Check if user_type param is null
if (user_type == null) {
res.status(500).send('`user_type` parameter is required');
return false;
}
// and so on for the other responses...
// then, if no condition produced an HTTP response...
return true;
}
然后在呼叫該函式時:
exports.findAll = (req, res) => {
if (!checkAuthorization(req, res, 'Customer')) {
// the function internally sent a response, stop processing
return;
}
db.User.findAll({ include: ['created', 'restaurant'] })
//...
};
順便說一句……這個整體邏輯結構很快就會讓人困惑。您可能想要做的是將您的checkAuthorization邏輯移動到它自己的中間件中,該中間件將在每個請求上呼叫,甚至在請求到達findAll這種情況下的邏輯之前。
在中間件管道中,您可以使用res向用戶發送回應然后結束處理,或呼叫next以繼續處理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/497505.html
標籤:javascript 节点.js 表示
上一篇:像這樣的警告:串列中的每個孩子都應該有一個唯一的“關鍵”道具
下一篇:react如何處理復雜的狀態
