當我嘗試使用電子郵件和密碼通過郵遞員發布此 API 時。
我得到User Not Found。我交叉檢查電子郵件和密碼 100 多次。
在命令提示符中,我收到UnhandledPromiseRejectionWarning: E??rror [ERR_HTTP_HEADERS_SENT]: 發送到客戶端后無法設定標頭。
我在這里做錯了什么。請告訴我,先謝謝你。
exports.loginUser = async (req, res) => {
try{
const user = await userTable.findOne({ email:req.body.email });
if (!user){
res.send({
status: 404,
message: "User Not Found"
});
}
const hashpass = cryptr.decrypt(user.password);
if (hashpass == req.body.password){
const accessToken = jwt.sign({ id: user._id, email: user.email }, process.env.JWT_PASS, {expiresIn:"1d"});
res.send({
status: 200,
data: user,
jwt: accessToken
});
}else{
res.send({
status: 404,
message: "Wrong password"
});
}
}catch(err){
res.status(500).send({
status: 0,
message: "catch issue" err.message
});
};
};
uj5u.com熱心網友回復:
我很確定這正在發生,因為您的處理程式在發送回應后繼續,因此在回應已經發送后嘗試修改回應。
請記住,這可能是您使用該loginUser功能的方式。如果您不介意更新您的問題,向我們展示您如何使用它,那將非常有幫助!
我想到了幾件事;1. 您可能需要在某處添加 return 陳述句,例如在第 10/11 行中的示例 2. 您還可以將代碼包裝在if陳述句中的第一個else陳述句之后,以查看是否會發生變化。
歸根結底,我很確定您的代碼在發送回應后會繼續運行,這就是您看到該錯誤的原因。
和 return
exports.loginUser = async (req, res) => {
try {
let dataToSend = {};
const user = await userTable.findOne({ email: req.body.email });
if (!user) {
res.send({
status: 404,
message: "User Not Found",
});
// Try adding this
return;
}
const hashpass = cryptr.decrypt(user.password);
if (hashpass == req.body.password) {
const accessToken = jwt.sign({ id: user._id, email: user.email }, process.env.JWT_PASS, { expiresIn: "1d" });
res.send({
status: 200,
data: user,
jwt: accessToken,
});
} else {
res.send({
status: 404,
message: "Wrong password",
});
}
} catch (err) {
res.status(500).send({
status: 0,
message: "catch issue" err.message,
});
}
};
包裹起來 else
這是非常丑陋的,我認為應該只用于測驗!
exports.loginUser = async (req, res) => {
try {
const user = await userTable.findOne({ email: req.body.email });
if (!user) {
res.send({
status: 404,
message: "User Not Found",
});
} else {
const hashpass = cryptr.decrypt(user.password);
if (hashpass == req.body.password) {
const accessToken = jwt.sign({ id: user._id, email: user.email }, process.env.JWT_PASS, { expiresIn: "1d" });
res.send({
status: 200,
data: user,
jwt: accessToken,
});
} else {
res.send({
status: 404,
message: "Wrong password",
});
}
}
} catch (err) {
res.status(500).send({
status: 0,
message: "catch issue" err.message,
});
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/361380.html
