2

I've manage to generate a token and even verify on the Server side. The issue I'm now having is, I can't return the token and redirect or render the page. I can do one or the other but not both! Seems like when one is used it calls an end and doesn't allow the second or it runs into sending header issues(ie header was already sent). Below is the code:

 else {
        //This res works fine on its own                    
          res.json({
                  success: true,
                  message: 'Enjoy your token!',
                  token:  token 
          });
        //This res works fine on its own
        res.redirect('/control');
    }
  • Why not redirect in the client when you get the token? Or set the token in a header then redirect? – Tony May 27 '15 at 15:43
  • The actual error I'm getting is: "Error: Can't set headers after they are sent". – Enrique Romero May 27 '15 at 17:03
  • That's because both `res.json` and `res.redirect` end the response. – Tony May 27 '15 at 17:07
  • So there is absolutely no way to use both of these together then? – Enrique Romero May 27 '15 at 17:39
  • No. Either the client needs to react to the json, or you need to separate the calls and add some middleware to add the token to the redirect, in which case the client most likely has the token. A third option, is `redirect('/control?token=' + token)` and then you can use `req.query.token` to do something with it. – Tony May 27 '15 at 17:42

1 Answers1

0

Below is the code which worked. Also found this link which explains in more details on the error I was getting. Tried some of it but none seem to work for me.

 success    : function(responseText, status, xhr, $form){
              if (status == 'success') 
                 window.location.href = '/' + '?token=' + token ;
Community
  • 1
  • 1