Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ajax - How to properly redirect in NodeJS/ExpressJS?

I am building a shopping cart application in nodejs/expressjs. I am having some issues with redirecting to the correct page after a user has signed in. I have found several articles that relate closely but all of my attempts to fix it from those given articles is not doing the trick.

    access: function(req, res){
  var data = JSON.parse(req.body.data);
  console.log(data);
      Customers.findOne({"custEmail": data.custEmail}, function(err, user){
        if(err){
          console.log(err);
          res.send("error");
        }if(!user){
          console.log("user not found");
          res.send("error");
        }else{
          console.log("user found");
          bcrypt.compare(data.custPassword, user.custPassword, function(err, reponse){
            if(reponse){
              req.session.regenerate(function(err){
                if(err){
                  console.log(err);
                  res.send("error");
                }else{
                  req.session.success = true;
                  res.send("Success");
                  //res.redirect('/');
                }
              });
            }else{
              console.log("error");
            }
          });
          }
      });

What happens is, a user enters their login information and clicks the login button. An Ajax request sends the data to this access function. The function starts by checking to see if the user exists in the database. If it does than it continues to compare the bcrypt password, if they are equal they successfully login and if they do not equal then obviously it errors out.

The issue seems to be here: }else{ req.session.success = true; res.send("Success"); //res.redirect('/'); }

When the user email and the password match this is hit right here. It says.. set this session to true, so the user can access pages where this session is required, and then sends a Success message back to the ajax request. This currently works perfectly fine and the res.send is sent to the front end. When I uncomment the res.redirect, the expected result of 'cannot set headers after they are set' happens. So when I comment out the res.send, the res.redirect simply ends up not working at all. No error, no breaking of anything just simply nothing.

I am curious to why this redirect here would not work? The headers are not being set anywhere else in this function and the expected result should be that the redirect would work perfectly fine. Any help is greatly appreciated. Thanks.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you send an ajax call with either XMLHttpRequest or fetch() and get the response, the browser does not do anything to the current page in the browser based on that response. So, it doesn't matter whether you send a redirect response to the ajax call or not. The browser won't change the current page in the browser, no matter what. Ajax responses generate data for your Javascript and your Javascript must then decide what to do with it.

FYI, the browser will change the current page only when the redirect happens from a browser page request or a browser submitted form post (not Javascript submitted). Since that is not how you are logging in, you can't use a redirect to change the current browser page.

So, if you're going to use an ajax call on the client for login and you want the client to change pages after a successful Ajax login, then you probably want to send the redirect URL in the login response and have the client process it and set window.location to do the redirect on login.

For example, you could change:

res.send("Success");

to this:

res.json({status: "Success", redirect: '/'});

And, then have your client code examine the return from the ajax call and if the status is successful, it can grab the redirect property and do something like:

if (ajaxResult.status === "Success") {
    window.location = ajaxResult.redirect;
}

I am curious to why this redirect here would not work? The headers are not being set anywhere else in this function and the expected result should be that the redirect would work perfectly fine. Any help is greatly appreciated.

The message about headers have already been sent means that the whole response has already been sent with res.send("Success"); and you are now trying to send another response. You only get one response for a given request. Once you've done res.send("Success");, the http server object has sent the whole response and then closed off that response. You can't send more data at that point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...