0
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,
        })
    }
}

[email protected] [Object: null prototype] { username: 'rohit', email: '[email protected]', password: 'Taptap@30', cnfrmPass: 'Tapesh@30' } null here 1 User created succesfully Error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (node:_http_outgoing:652:11) at ServerResponse.header (C:\Users\rohan\OneDrive\Documents\CODES\pinetree\Backend\node_modules\express\lib\response.js:794:10) at ServerResponse.send (C:\Users\rohan\OneDrive\Documents\CODES\pinetree\Backend\node_modules\express\lib\response.js:174:12) at ServerResponse.json (C:\Users\rohan\OneDrive\Documents\CODES\pinetree\Backend\node_modules\express\lib\response.js:278:15) at C:\Users\rohan\OneDrive\Documents\CODES\pinetree\Backend\app.js:98:36 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async C:\Users\rohan\OneDrive\Documents\CODES\pinetree\Backend\app.js:94:9 {
code: 'ERR_HTTP_HEADERS_SENT' } node:_http_outgoing:652 throw new ERR_HTTP_HEADERS_SENT('set'); ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (node:_http_outgoing:652:11) at ServerResponse.header (C:\Users\rohan\OneDrive\Documents\CODES\pinetree\Backend\node_modules\express\lib\response.js:794:10) at ServerResponse.send (C:\Users\rohan\OneDrive\Documents\CODES\pinetree\Backend\node_modules\express\lib\response.js:174:12) at ServerResponse.json (C:\Users\rohan\OneDrive\Documents\CODES\pinetree\Backend\node_modules\express\lib\response.js:278:15) at C:\Users\rohan\OneDrive\Documents\CODES\pinetree\Backend\app.js:108:25 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'ERR_HTTP_HEADERS_SENT' }

Node.js v20.10.0 [nodemon] app crashed - waiting for file changes before starting...

I have been trying to get otp using nodemailer but i am facing this issue when i'm trying to make a new user. After the user is created the code shows the following error. I tried to resolve it but i haven't able to do so untill now. Thanks for the help!

1 Answer 1

0

You are sending a response from the server to the client twice: first response is sent from sendOTPVerificationEmail function (using res.json) after email was sent, and then another response is sent from the signup router (using res.send)

Change your code to send a single response for a single HTTP request. For example, you can refactor sendOTPVerificationEmail to return an object instead of directly call res.json and send it to client

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.