如何在NodeJS/ExpressJS中正确重定向? [英] How to properly redirect in NodeJS/ExpressJS?

查看:848
本文介绍了如何在NodeJS/ExpressJS中正确重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在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");
            }
          });
          }
      });

发生的事情是,用户输入他们的登录信息,然后单击登录按钮. Ajax请求将数据发送到此访问功能.该功能首先检查用户是否存在于数据库中.如果是的话,它将继续比较bcrypt密码,如果密码相等,则表示成功登录;如果密码不相等,则显然会出错.

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.

问题似乎在这里:}else{ req.session.success = true; res.send("Success"); //res.redirect('/'); }

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

当用户电子邮件和密码匹配时,将在此处单击.它说..将此会话设置为true,以便用户可以访问需要该会话的页面,然后将成功消息发送回ajax请求.目前,这可以正常工作,并且res.send发送到前端.当我取消注释res.redirect时,会发生设置头后无法设置头"的预期结果.因此,当我注释掉res.send时,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.

推荐答案

发送ajax调用并获取响应时,浏览器不会基于该ajax响应对浏览器中的当前页面执行任何操作.因此,是否向ajax调用发送重定向响应都没有关系.无论如何,浏览器都不会更改浏览器中的当前页面. Ajax响应会为您的Javascript生成数据,然后您的Javascript必须决定如何处理它.

When you send an ajax call and get the response, the browser does not do anything to the current page in the browser based on that ajax 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.

仅供参考,仅当从浏览器页面请求或浏览器提交的表单发布(未提交Java脚本)进行重定向时,浏览器才会更改当前页面.因为这不是您的登录方式,则不能使用重定向更改当前的浏览器页面.

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.

因此,如果您要在客户端上使用ajax调用进行登录,并且希望客户端在Ajax成功登录后更改页面,那么您可能希望在登录响应中发送重定向URL并获得客户端处理它,并设​​置window.location以便在登录时进行重定向.

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.

例如,您可以更改:

res.send("Success");

对此:

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

然后,让您的客户端代码检查ajax调用的返回结果,如果状态成功,则它可以获取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.

有关标头的消息已经发送,意味着整个响应已经通过res.send("Success");发送,您现在正尝试发送另一个响应.对于给定的请求,您只会收到一个答复.完成res.send("Success");后,http服务器对象已发送了整个响应,然后关闭了该响应.此时您无法发送更多数据.

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.

这篇关于如何在NodeJS/ExpressJS中正确重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆