Search code examples
node.jsexpresshttp-redirectes6-promise

res.redirect is not a function in promise then


I use node v8.11.1 with express 4.16.3 and postgresql as my database, so I use the pg module. I am new to promises and then. This is my code that should work

the route

 router.post('/save',
(req, res)=>{
  req.checkBody('email', 'put email').notEmpty().trim();
  let errors = req.validationErrors();
  if (errors) {
    req.session.msgs = errors;
    res.redirect('/signup');
   }
   else {
     var user = {email:req.body.email};
     signup.signup(user)
     .then((res)=>{           
       req.session.msgs = [{msg: res}];
       res.redirect('/events');
       },
       (rej)=>{
         res.redirect('/signup');
         req.session.msgs = [{msg: 'err'}];
       }
     )
     .catch((err)=>{
       res.redirect('/signup');
       req.session.msgs = [{msg: 'err'}];
     });
   }
});

the function

const signup = (user) => {
  return new Promise((res, rej)=>{
    pool.connect( //connect to db
      (err, client, done) => {
        if (err) {
          return rej(err); //rej
        }
        client.query('insert into user (email) values($1)',[user.email]);
        done();
        res(user.email);
      }// pool anonumous funct
    );//pool connect
  })//promise
};
exports.signup = signup;

So , I guess this should work right away, but I am getting err TypeError: res.redirect is not a function that refers to my route, in this part

     signup.signup(user)
     .then((res)=>{           
       req.session.msgs = [{msg: res}];
       res.redirect('/events'); // <= REFERS HERE
       },

What am I missing? Why is this not a function? How to fix this? Thank you


Solution

  • You're using a res in the then callback, and that one shadows the res from the router.post.

    So you need to rename one of those.