[英]Cannot set headers after they are sent to the client (Node.js)
所以基本上,當我嘗試登錄用戶時輸入錯誤的密碼或用戶名,然后嘗試使用正確的憑據登錄時,我會收到此錯誤。
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (D:\ecom website\ecom backend\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (D:\ecom website\ecom backend\node_modules\express\lib\response.js:174:12)
at ServerResponse.json (D:\ecom website\ecom backend\node_modules\express\lib\response.js:278:15)
at D:\ecom website\ecom backend\routes\auth.js:57:21
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
這是我在 auth.js 中的代碼
//LOGIN
router.post('/login', async (req, res) => {
try {
const user = await User.findOne({
username: req.body.username,
});
!user && res.status(401).json('Wrong User Name');
const hashedPassword = CryptoJS.AES.decrypt(
user.password,
process.env.PASS_SEC
);
const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
const inputPassword = req.body.password;
originalPassword != inputPassword && res.status(401).json('Wrong Password');
const accessToken = jwt.sign(
{
id: user._id,
isAdmin: user.isAdmin,
},
process.env.JWT_SEC,
{ expiresIn: '3d' }
);
const { password, ...others } = user._doc;
res.status(200).json({ ...others, accessToken });
} catch (err) {
res.status(500).json(err);
}
});
我應該怎么辦? 我的代碼有問題嗎?
.user && res.status(401);json('Wrong User Name');
作為聲明是恕我直言,相當糟糕的風格。 如您所見,它會導致錯誤,因為您的代碼在發送標頭后不會跳出此處理程序。 它只是繼續下一個語句並最終到達另一個res.status(...)
。 這將嘗試再次設置一些標頭,這是不允許的。 這就是錯誤消息告訴您的內容。
采用
if (!user) {
return res.status(401).json('Wrong User Name');
}
反而。 這將從處理程序返回,並且不會執行 function 中的剩余代碼......當然對於您使用此模式的所有其他實例也是如此。
我看到您在代碼中多次使用res.status(code).json(content)
命令,但在發送響應后您從未退出 function。 結果,在一個這樣的命令之后 - 代碼將在 function 中繼續並嘗試發送另一個響應,這就是您收到錯誤的地方:服務器正在嘗試為一個請求發送多個響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.