简体   繁体   中英

How do I find the previous URL for login using pure JavaScript? document.referrer is not working for me

I am using express with pug templates and pure JavaScript,for the log in system I want to save the URL someone came to the login page with so I can move them back to it after they finish to log in, however I can't find it.

I tried using document.referrer and put it inside an hidden input to store it inside the pug template,it responded with an error message saying document is not defined, type error, when I rendered the login page.do I need to define something or download some module for me to use document properties? if I simply cant do it that way how can I do it?

here is my get route handler in the my router:

router.get('/login', function(req,res,next) {
  res.render('login', {backUrl: document.referrer});
}); 

Thanks!

You can get the referrer in Express.js:

req.get('Referrer')

If you want to redirect after login, you can add query string to your login URL and you can redirect the page after login.

You can add the current page at the end of the URL.

Let's say user browsing " /view-documents " page. After user click login button add the current path to login URL like this:

/login?redirect=/view-documents

and you can redirect like this:

router.get('/login', function(req,res,next) {
  res.redirect(req.query.redirect);
}); 

Query strings tutorial

req.originalUrl

According to express documentation:

This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM