Gamox
Gamox

Reputation: 13

Node Express.js Middleware, end Response

validateRegister: async (req, res, next) => {

        UserModel.findOne({email:req.body.email}, (err, example) => {
            console.log(example);
            if(err) console.log(err);
            if(example) {
                res.status(400).json({message: "Email already registered!"});
                res.end() //next('route')
            }
        });
        console.log("test");
        const user = new UserModel(req.body);
        await user.save((err) => {
            if (err) return res.status(500).json({ message: "Database issue!" });
        }); 

        next();
    },

Ok, I tried to insert user data if it is not already in the database using mongoose. If the User regarding the email is already in the database the response should be ended and the user not inserted. I tried to end the response with res.end() and next('route'), but nothing seems to work, the console.log("test") still runs.

Error:

events.js:353
      throw er; // Unhandled 'error' event
      ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:561:11)

Thanks for your help

Upvotes: 1

Views: 793

Answers (2)

Sourabh Kumar
Sourabh Kumar

Reputation: 44

Code below callback function gets executed before callback gets completed and multiple res.send happened.

you can try this

validateRegister: async (req, res, next) => {

UserModel.findOne({ email: req.body.email }, (err, example) => {
    console.log(example);
    if (err) {
        console.log(err);
        return res.status(500).json({ message: "Something went wrong" });

    }
    if (example) {
        return res.status(400).json({ message: "Email already registered!" });
    }
    console.log("test");
    const user = new UserModel(req.body);
    await user.save((err) => {
        if (err) return res.status(500).json({ message: "Database issue!" });
    });
});

next();
}

Or

validateRegister: async (req, res, next) => {
try {
    let example = await UserModel.findOne({ email: req.body.email });
    console.log(example);
    if (example)
        return res.status(400).json({ message: "Email already registered!" });
    console.log("test");
    const user = new UserModel(req.body);
    await user.save((err) => {
        if (err) return res.status(500).json({ message: "Database issue!" });
    });
    next();
} catch (err) {
    console.log(err);
    return res.status(500).json({ message: "Something went wrong" });
}
}

Upvotes: 2

Smriti Shikha
Smriti Shikha

Reputation: 431

you can add return before returning response in the case of user email already found.

What seems to happen is that your program is calling res two times

Upvotes: 0

Related Questions