res.redirect('back')与参数 [英] res.redirect('back') with parameters

查看:903
本文介绍了res.redirect('back')与参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我网站的每个页面都有一个注册表。注册期间可能会发生错误。捕捉错误后,我必须将用户返回到上一页,显示一些错误消息。问题是我不知道用户执行注册的页面,所以我使用 res.redirect('back'); 。但是,我不能只是重定向用户,我也必须显示错误信息,所以我必须传递一些参数。但是 res.redirect('back',(reg_error:'username')})不能直接使用,因为 res.redirect()不支持参数。如何使用某些参数呈现上一页?

解决方案

使用引用头来查找您的用户来自哪个页面可能是帮助:

  app.get('/ mobileon',function(req,res){
backURL = req。标题('Referer')||'/';
//你的thang
res.redirect(backURL);
});

您可能还想将 backURL req.session,如果您需要它在多个路由上持久化。记住测试该变量的存在,如下所示: res.redirect(req.session.backURL ||'/')






编辑:由于我的答案已经得到一些upvote,我输入了我目前的方式来做到这一点。它有一点时间,以便您可以在 https://gist.github.com/therealplato/7997908 查看。



最重要的区别是在覆盖Referer url的查询字符串中使用显式的bounce参数。


I have a register form on every page of my website. During registration some error may occur. After catching the error, I have to return the user to the previous page, showing some error message. The problem is that I do not know from which page the user performed the registration, so I use res.redirect('back');. However, I cannot just redirect user back, I have to display the error message also, so I have to pass some argument. But res.redirect('back', (reg_error:'username')}) cannot be used directly because res.redirect() does not support parameters. How can I render the previous page with some parameter?

解决方案

Using the referer header to find what page your user came from might be helpful:

app.get('/mobileon', function(req, res){
  backURL=req.header('Referer') || '/';
  // do your thang
  res.redirect(backURL);
});

You might also want to store backURL in req.session, if you need it to persist across multiple routes. Remember to test for the existence of that variable, something like: res.redirect(req.session.backURL || '/')


edit: Since my answer has been getting some upvotes I typed up my current way to do this. It got a little long so you can view it at https://gist.github.com/therealplato/7997908 .

The most important difference is using an explicit 'bounce' parameter in the query string that overrides the Referer url.

这篇关于res.redirect('back')与参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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