res.redirect('back') with parameters

后端 未结 7 2024
刺人心
刺人心 2020-12-23 09:44

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, sho

7条回答
  •  被撕碎了的回忆
    2020-12-23 10:20

    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.

提交回复
热议问题