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

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

问题描述

我正在 nodejs/expressjs 中构建一个购物车应用程序.我在用户登录后重定向到正确页面时遇到了一些问题.我发现了几篇密切相关的文章,但我从这些给定文章中修复它的所有尝试都没有奏效.

 访问:function(req, res){var data = JSON.parse(req.body.data);控制台日志(数据);Customer.findOne({"custEmail": data.custEmail}, function(err, user){如果(错误){控制台日志(错误);res.send("错误");}如果(!用户){console.log("找不到用户");res.send("错误");}别的{console.log("找到用户");bcrypt.compare(data.custPassword,user.custPassword,函数(错误,响应){如果(响应){req.session.regenerate(功能(错误){如果(错误){控制台日志(错误);res.send("错误");}别的{req.session.success = true;res.send("成功");//res.redirect('/');}});}别的{console.log("错误");}});}});

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

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

当用户电子邮件和密码匹配时,就会在此处点击.它说.. 将此会话设置为 true,以便用户可以访问需要此会话的页面,然后将 Success 消息发送回 ajax 请求.这目前工作得很好,并且 res.send 被发送到前端.当我取消注释 res.redirect 时,会出现设置标题后无法设置标题"的预期结果.因此,当我注释掉 res.send 时,res.redirect 最终根本不起作用.没有错误,没有破坏任何东西,只是什么都没有.

我很好奇为什么这里的重定向不起作用?在此函数中的其他任何地方都没有设置标头,预期的结果应该是重定向可以正常工作.任何帮助是极大的赞赏.谢谢.

解决方案

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

仅供参考,仅当重定向发生在浏览器页面请求或浏览器提交的表单帖子(未提交 Javascript)时,浏览器才会更改当前页面. 因为这不是您登录的方式,您不能使用重定向来更改当前浏览器页面.

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

例如,您可以更改:

res.send(成功");

为此:

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

然后让您的客户端代码检查 ajax 调用的返回,如果状态成功,它可以获取重定向属性并执行以下操作:

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

<块引用>

我很好奇为什么这里的重定向不起作用?标题是未在此函数和预期结果中的其他任何地方设置应该是重定向可以正常工作.任何帮助是非常感谢.

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

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.

解决方案

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.

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

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