app.post("/login", async (req, res) => {
// Destructure Req Body
const { email, password } = req.body;
// Validate Body
if (!email || !password) {
res.status(400).json({ success: false, message: "PARAMS_MISSING" });
}
// Build the SQL query
const query = `SELECT * FROM user WHERE email = "${email}"`;
// Get the user from DB
const user = await db(query);
// Check if password is valid
const isPasswordValid = decryptPassword(user.hash_password, password);
// Return if password is not valid
if (!isPasswordValid) {
res.status(401).json({ success: false, message: "INAVLID_PASSWORD" });
}
// Generate Token
const token = generateToken({ id: user.id, email: user.email });
// Save Cookie
res.cookie("token", token, { maxAge: 900000, httpOnly: true });
res.end();
// Return
res.json({ success: true, message: "USER_AUTHENTICATED" });
});
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
我再次收到此错误 n 再次idk 我是初学者该怎么办, 与 Passport.js、Express 一起使用时,我在 NodeJS 中遇到了这个奇怪的问题。基本上,即使我不发送多个标头,我也会收到一条错误消息,指出“在将标头发送到客户端后无法设置标头”。
答案 0 :(得分:0)
这个错误意味着“res”对象响应了两次。例如:在您的 '// Validate body
' 中,如果密码或电子邮件丢失,您的 http 连接响应 'res.status().json()
.'(注意正在关闭 http 连接),但由于您没有停止执行代码,它继续然后它可能会在创建错误的 // Return if password is not valid
中第二次响应,因为标头不能设置两次并且连接已经关闭。
这里的错误更多的是未处理,作为异步函数拒绝,错误必须得到处理,将代码包装在 try{} catch(e){} 中将修复它。
这样应该可以解决您的问题
app.post("/login", async (req, res) => {
try{
// Destructure Req Body
const { email, password } = req.body;
// Validate Body
if (!email || !password) {
res.status(400).json({ success: false, message: "PARAMS_MISSING" });
return // stop execution of the function
}
// Build the SQL query
const query = `SELECT * FROM user WHERE email = "${email}"`;
// Get the user from DB
const user = await db(query);
// Check if password is valid
const isPasswordValid = decryptPassword(user.hash_password, password);
// Return if password is not valid
if (!isPasswordValid) {
res.status(401).json({ success: false, message: "INAVLID_PASSWORD" });
return // stop exec of the function
}
// Generate Token
const token = generateToken({ id: user.id, email: user.email });
// Save Cookie
res.cookie("token", token, { maxAge: 900000, httpOnly: true });
res.end();
// Return
res.json({ success: true, message: "USER_AUTHENTICATED" });
} catch(err) {
console.error(err) // code to handle the err
}
});
但是,脚本末尾仍然存在一个问题,您有一个 res.end()(终止连接),紧接着 res.json() 将失败,因为连接已关闭前一行(比 statusCode 丢失更多)