错误:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头。 (nodemailer-emailVerification)

问题描述 投票:0回答:1
app.post("/signup", async (req, res) => {
    // console.log(req.body)
    const { username, email, password, cnfrmPass } = req.body;
    // console.log(cnfrmPass)
    const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{8,}$/;
    if (!passwordRegex.test(password)) {
        return res.status(400).json({ error: 'Password does not meet the criteria' });
    }
    try {
        console.log(email)
        console.log(req.body);
        const existingUser = await userModel.findOne({ email });
        console.log(existingUser)
        // Existing user
        console.log("here 1")
        if (existingUser) {
            console.log("Existing User")
            return res.status(400).json({ error: 'User already exists' });
        }
        // Create a new user
        const newUser = new userModel({ username, email, password });
        console.log("User created succesfully")
        await newUser
        .save()
        .then((newUser) => {
            sendOTPVerificationEmail(newUser, res)
            return res.status(201).json({ message: 'User created successfully' });
        })
        // const result = await newUser.save();

        // // Send OTP verification email
        // await sendOTPVerificationEmail(result, res);
    
        return res.status(201).json({ message: 'User created successfully' });
    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
})
const sendOTPVerificationEmail = async (req, res) => {
    try {
        const otp = `${Math.floor(1000 + Math.random() * 9000)}`;
        const mailOptions = {
            from: process.env.AUTH_EMAIL,
            to: email,
            subject: "Verify your Email",
            html: `<p>Enter <b>${otp}</b> in the app to verify your email address and complete </p>
            <p>This code <b>expires in 1 hour</b>.</p>`,
        };

        const saltRounds = 10;
        const hashedOTP = await bcrypt.hash(otp, saltRounds);
        const newOTPVerification = await new UserOTPVerification({
            userId: _id,
            otp: hashedOTP,
            createdAt: Date.now(),
            expiresAt: Date.now() * 3600000,
        });
        await newOTPVerification.save();
        await transporter.sendMail(mailOptions);
        res.json({
            status: "PENDING",
            message: "Verification otp email sent",
            data: {
                userId: _id,
                email,
            }
        })
    }
    catch (error) {
        res.json({
            status: "FAILED",
            message: error.message,
        })
    }
}

[电子邮件受保护] [对象:空原型] { 用户名:'罗希特', 电子邮件:'[电子邮件受保护]', 密码:'Taptap@30', cnfrmPass: 'Tapesh@30' } 无效的 这里 1 用户创建成功 错误:错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 在 ServerResponse.setHeader (节点:_http_outgoing:652:11) 在 ServerResponse.header (C:\Users ohan\OneDrive\Documents\CODES\pinetree\Backend ode_modules xpress\lib esponse.js:794:10) 在 ServerResponse.send (C:\Users ohan\OneDrive\Documents\CODES\pinetree\Backend ode_modules xpress\lib esponse.js:174:12) 在 ServerResponse.json (C:\Users ohan\OneDrive\Documents\CODES\pinetree\Backend ode_modules xpress\lib esponse.js:278:15) 在 C:\Users ohan\OneDrive\Documents\CODES\pinetree\后端 pp.js:98:36 在 process.processTicksAndRejections (节点:内部/进程/task_queues:95:5)
在异步 C:\Users ohan\OneDrive\Documents\CODES\pinetree\Backend pp.js:94:9 {
代码:'ERR_HTTP_HEADERS_SENT' } 节点:_http_传出:652 抛出新的 ERR_HTTP_HEADERS_SENT('set'); ^

错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头
在 ServerResponse.setHeader (节点:_http_outgoing:652:11) 在 ServerResponse.header (C:\Users ohan\OneDrive\Documents\CODES\pinetree\Backend ode_modules xpress\lib esponse.js:794:10) 在 ServerResponse.send (C:\Users ohan\OneDrive\Documents\CODES\pinetree\Backend ode_modules xpress\lib esponse.js:174:12) 在 ServerResponse.json (C:\Users ohan\OneDrive\Documents\CODES\pinetree\Backend ode_modules xpress\lib esponse.js:278:15) 在 C:\Users ohan\OneDrive\Documents\CODES\pinetree\后端 pp.js:108:25 在 process.processTicksAndRejections (节点:内部/进程/task_queues:95:5){
代码:'ERR_HTTP_HEADERS_SENT' }

Node.js v20.10.0 [nodemon] 应用程序崩溃 - 启动前等待文件更改...

我一直在尝试使用nodemailer 获取otp,但当我尝试创建新用户时遇到这个问题。创建用户后,代码显示以下错误。我试图解决它,但直到现在我还无法做到这一点。感谢您的帮助!

node.js mern nodemailer email-validation
1个回答
0
投票

您从服务器向客户端发送两次响应:第一次响应是在发送电子邮件后从

sendOTPVerificationEmail
函数(使用
res.json
)发送的,然后另一个响应是从注册路由器发送的(使用
res.send

更改代码以针对单个 HTTP 请求发送单个响应。例如,您可以重构

sendOTPVerificationEmail
以返回一个对象,而不是直接调用
res.json
并将其发送给客户端

© www.soinside.com 2019 - 2024. All rights reserved.