创建一个登录功能,我发送后使用 Postman 发送正确的电子邮件和密码的请求没有错误,但在我尝试发送错误的密码,然后有这个错误发送错误的电子邮件或密码,然后得到了错误。我读了互联网上的大多数职位,但没有解决我的问题。我在YouTube视频中复制了该代码,该视频中没有错误
{
"email": "testx@gmail.com",
"password": "1x23456"
}
MongoDB Connection Successfully
node:internal/errors:490
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:399:5)
at ServerResponse.setHeader (node:_http_outgoing:644:11)
at ServerResponse.header (C:\Users\Madhawa\Desktop\Social Media Project\Server\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (C:\Users\Madhawa\Desktop\Social Media Project\Server\node_modules\express\lib\response.js:174:12)
at ServerResponse.json (C:\Users\Madhawa\Desktop\Social Media Project\Server\node_modules\express\lib\response.js:278:15)
at login (file:///C:/Users/Madhawa/Desktop/Social%20Media%20Project/Server/controllers/Auth.js:21:25)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
Node.js v19.8.1
[nodemon] app crashed - waiting for file changes before starting...
这是我的代码
import CryptoJS from "crypto-js";
import User from "../models/user.js";
import Jwt from "jsonwebtoken";
// login function
export const login = async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
if (!user) {
res.status(404).json(" User not found ");
}
const decryptedPassword = await CryptoJS.AES.decrypt(user.password, process.env.SECRET_KEY).toString(CryptoJS.enc.Utf8);
if (decryptedPassword !== req.body.password) {
res.status(401).json("Wrong password ");
}
res.status(200).json(user);
} catch (error) {
res.status(500).json(error);
}
}
// register function
export const register = async (req, res) => {
try {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: CryptoJS.AES.encrypt(req.body.password, process.env.SECRET_KEY).toString(),
});
const user = await newUser.save();
res.status(201).json(user);
} catch (err) {
res.status(500).json(err);
}
}
export const logout = (req, res) => {
res.send("GET Logout");
}
export const glogin = (req, res) => {
res.send("POST Google Login");
}
1条答案
按热度按时间h43kikqp1#
必须使用“return”语句来确保函数执行在发送响应后立即结束。因为你没有使用“return”,程序在密码不正确的情况下仍然继续执行,导致了你提到的错误。