I am trying to implement login feature in Express.js version 4 app. I need to determine whether an user is logged in before he can do certain actions. So I have a middleware called as isLoggedIn which solely checks if user object is in session, if not, the user is redirected to login page. After the user successfully logs in, he must be redirected to the original URL.
app.get('/someaction', isLoggedIn, 'actual function to be executed'); Now inside isLoggedIn method, I see that req.url and req.originalUrl contains the requested action. However if the user is not logged in, when redirected to /login page, both req.url and req.originalUrl has /login as the contents. From what I read here, I can override req.url for internal routing purposes. But in my case both req.url and req.originalUrl gets overridden by /login action.
What am I doing wrong?
The req.originalUrl property is much like req.url however, it retains the original request URL thereby allowing you to rewrite req.url freely for internal routing purposes.
The req. body object allows you to access data in a string or JSON object from the client side. You generally use the req. body object to receive data through POST and PUT requests in the Express server.
urlencoded() is a built-in middleware in Express. js. The main objective of this method is to parse the incoming request with urlencoded payloads and is based upon the body-parser. This method returns the middleware that parses all the urlencoded bodies.
query is a request object that is populated by request query strings that are found in a URL. These query strings are in key-value form. They start after the question mark in any URL.
From the Express.js documentation:
req.urlis not a native Express property, it is inherited from Node’shttpmodule.This property is much like
req.url; however, it retains the original request URL, allowing you to rewritereq.urlfreely for internal routing purposes. For example, the “mounting” feature ofapp.use()will rewritereq.urlto strip the mount point.
In other words, req.url might be overwritten during the internal routing, while req.originalUrl will remain untouched.
The problem is that there are actually two entirely separate requests coming in to your server. The request for the /login page doesn't know anything about the page that the client requested before that. So when you redirect to the /login page, you need to save information about the originally-requested URL somewhere. I know of 2 solutions:
Some fancy work with session states allowing you to save the original URL as a variable, probably using promises.
Add the original URL as a query parameter to the /login request.
Check out this answer: How do I find original request path before redirect Express 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With