简体   繁体   中英

Can I access cookie from ejs page in server-side not the browser-side?

I need to make routine for checking login status under an environment - node.js, express, ejs.

I think I need to check login status in all the ejs view pages in server-side not in the browser-side.

To do this I think I need to write a code in ejs pages that find and look a cookie - this cookie proves the user has login properly.

Can I access browser cookie from ejs page?

If so, could you guide me how to access cookie from ejs page?

Can I use cookie-parser module from ejs?

If there is no way to access cookie from server-side in ejs page, I believe I only have to access cookie in browser-side. Is this normal way to handle login?

So you want to track user's session. You can do the following to achieve this.

When user logged in successfully with right credentials then add that user details to session.

if(loginSuccess){
    req.session.user = userObject;
}

Add a middleware to read user from session and put it into res.locals so that you can access the userObject in ejs files.

app.use(function(req, res, next) {
    res.locals.user = req.session.user;
    next();
});

Now you will have the userObject available in your ejs file so write your logic accordingly in ejs file. Let say if you want to display login when user not logged in and logout when your logged in, you can add code something like below

 <% if(user && user.email){ %>
    <a href="/logout">Logout</a>
 <% } else { %>
    <a href="/login">Login</a>
 <% } %>

Browser Cookie values can be found in req.headers.cookie .

For Example :

Print cookie in console:

router.get("/example"), (req, res) => { console.log(req.headers.cookie); }

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