简体   繁体   English

我可以从服务器端而不是浏览器端的 ejs 页面访问 cookie 吗?

[英]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.我需要例行检查环境下的登录状态 - 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.我想我需要在服务器端而不是浏览器端检查所有 ejs 视图页面中的登录状态。

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.为此,我想我需要在 ejs 页面中编写一个代码来查找并查看 cookie - 这个 cookie 证明用户已正确登录。

Can I access browser cookie from ejs page?我可以从 ejs 页面访问浏览器 cookie 吗?

If so, could you guide me how to access cookie from ejs page?如果是这样,您能否指导我如何从 ejs 页面访问 cookie?

Can I use cookie-parser module from ejs?我可以使用 ejs 中的 cookie-parser 模块吗?

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.如果没有办法在ejs页面从服务器端访问cookie,我相信我只需要在浏览器端访问cookie。 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.添加一个中间件从会话中读取用户并将其放入 res.locals 以便您可以访问 ejs 文件中的 userObject。

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.现在您将在 ejs 文件中使用 userObject,因此在 ejs 文件中相应地编写您的逻辑。 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 .浏览器 Cookie 值可以在req.headers.cookie找到。

For Example :例如:

Print cookie in console:在控制台打印 cookie:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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