在快速发送到客户端后不能设置标头



我注册成功,插入记录在我的mongodb,但当我尝试登录错误发生在网上"!用户,,res.status(401).json("用户名错误");";

Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/home/hahp1908/EShopAPI/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/home/hahp1908/EShopAPI/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/home/hahp1908/EShopAPI/node_modules/express/lib/response.js:278:15)
at /home/hahp1908/EShopAPI/routes/auth.js:42:25
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
const router = require('express').Router();
const User = require("../models/User");
const CrytoJS = require("crypto-js");
router.post('/login', async (req, res) => {
try{
const user = await User.findOne(
{
username: req.body.user_name
}
);
!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");
res.status(200).json(user);
}catch(err){
res.status(500).json(err);
}
});
module.exports = router

调用res.status().json()时需要结束函数的执行,否则它将继续执行,您将再次设置res.status().json()。这将导致错误。

修改为:

const router = require('express').Router();
const User = require("../models/User");
const CrytoJS = require("crypto-js");
router.post('/login', async (req, res) => {
try{
const user = await User.findOne(
{
username: req.body.user_name
}
);
if(!user) return 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;

if(originalPassword != inputPassword) return res.status(401).json("Wrong Password");
return res.status(200).json(user);
}catch(err){
return res.status(500).json(err);
}
});
module.exports = router

最新更新