Home > Software design >  Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client please solove th
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client please solove th

Time:07-05

Sir i'm facing this issue in nodejs, expressjs while registring a user in database. we here making a pizza ordring app .

here is issue:

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (D:\expressJsBySujeet\Realtime-pizza\node_modules\express\lib\response.js:794:10)
    at ServerResponse.location (D:\expressJsBySujeet\Realtime-pizza\node_modules\express\lib\response.js:915:15)
    at ServerResponse.redirect (D:\expressJsBySujeet\Realtime-pizza\node_modules\express\lib\response.js:953:18)
    at D:\expressJsBySujeet\Realtime-pizza\app\http\controllers\authController.js:40:32
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

here is my code authController.js:

async newUserregister(req, res) {
  const { Uname, email, password } = req.body; // getting data as array distructing
  if (
    !req.body.Uname.trim().length == 0 &&
    !req.body.email.trim().length == 0 &&
    !req.body.password.trim().length == 0
  ) {
    // check email exist or not
    newUser.exists({ email: email }, (err, result) => {
      if (result) {
        req.flash("error", "This Email Already exists");
        req.flash("Uname", Uname);
        req.flash("email", email);
        return res.redirect("/register");
      }
    });
    // create new user in data base
    const encPass = await bcrypt.hash(password, 10);
    const user = new newUser({
      Uname: Uname,
      email: email,
      password: encPass,
    });
    user
      .save()
      .then((user) => {
        console.log(user);
        return res.redirect("/ac");
      })
      .catch((err) => {
        req.flash("error", "something went wrong");
        return res.redirect("/register");
      });
  } else {
    req.flash("error", "All fields are required");
    req.flash("Uname", Uname);
    req.flash("email", email);

    return res.redirect("/register");
  }
}

line no 40 is start with :

req.flash('error','something went wrong')
return res.redirect('/register')

i'm creating a user register system in expressjs please answer how this will fixed

CodePudding user response:

Wait until you've finished checking if the user exists or not before creating a new user - otherwise, if you do res.redirect('/register') and then do the same thing later, you'll have redirected twice. Only redirect exactly once.

You should also check if the .exists call throws an error, instead of ignoring it.

async newUserregister(req, res){
    const { Uname, email, password } = req.body;
    if (!Uname.trim().length || !email.trim().length || !password.trim.length) {
        req.flash('error', 'All fields are required')
        req.flash('Uname', Uname)
        req.flash('email', email)
        return res.redirect('/register')
    }
    newUser.exists({ email }, (err, result) => {
        if (err) {
            req.flash('error', 'something went wrong')
            return res.redirect('/register')
        }
        if (result) {
            req.flash('error', 'This Email Already exists')
            req.flash('Uname', Uname)
            req.flash('email', email)
            return res.redirect('/register')
        }
        bcrypt.hash(password, 10)
            .then((encPass) => {
                const user = new newUser({
                    Uname,
                    email,
                    password: encPass
                })
                return user.save();
            })
            .then((user) => {
                console.log(user)
                res.redirect('/ac')
            })
            .catch(err => {
                req.flash('error', 'something went wrong')
                res.redirect('/register')
            });
    });
}

The syntax gets a lot easier if .exists returns a Promise, or you can change to a Promise-based version of it - then you can catch only at the end, and await all the Promises. Something like:

async newUserregister(req, res){
    const { Uname, email, password } = req.body;
    if (!Uname.trim().length || !email.trim().length || !password.trim.length) {
        req.flash('error', 'All fields are required')
        req.flash('Uname', Uname)
        req.flash('email', email)
        return res.redirect('/register')
    }
    try {
        const userAlreadyExists = await newUser.exists({ email });
        if (userAlreadyExists) {
            req.flash('error', 'This Email Already exists')
            req.flash('Uname', Uname)
            req.flash('email', email)
            return res.redirect('/register')
        }
        const encPass = await bcrypt.hash(password, 10);
        const user = new newUser({
            Uname,
            email,
            password: encPass
        })
        await user.save();
        console.log(user)
        res.redirect('/ac')
    } catch (err) {
        req.flash('error', 'something went wrong')
        res.redirect('/register')
    }
}
  • Related