如何解决如何强制 Node.js 在登录时不显示我的登录按钮并在注销时显示它
当用户登录时,create
更改为 localStorage
,因此我希望按钮在变量更改为 req.session.loggedin
时消失/出现。简而言之,我想知道如何从 Node.js 文件更改 pug 文件中的 true
变量。
true
这是我的 .pug
loggedin
如果您有任何问题,请不要害怕提问。
解决方法
所以我可以注意到您的代码中存在一些问题:
- 你不需要 if 语句,
req.session.loggedin
应该已经是布尔值了 -
app.locals.loggedin
应该是res.locals.loggedin
您的代码应如下所示:
服务器:
app.use(function(req,res,exit) {
res.locals.loggedin = req.session.loggedin;
//Im not sure for what this line for therefore i leave it here.
res.app.use(express.static(path.join(__dirname,'/site/data')))
exit();
})
客户:
li
a(href='/') Home
li
a(href='/about') About
li
a(href='/contact') Contact
if loggedin
li
a(href='/logout') Logout
else
li
a(href='/login') login
你需要确保你的服务器端代码中有一些东西:
请不要忘记在您的登录后功能中添加此行(可能已经存在)
req.session.loggedin= true;
此外,您还需要确保 app.js 上有会话中间件
//The secret you might want to store in .env file.
const session = {
secret: 'SUPER_SECRET_KEY',cookie: {},resave: true,saveUninitialized: true
};
//this will check if you are on development or production. and secure the cookie
//(session) if you are on production. (if you will not deploy your app its not a
//must to add it)
if (app.get("env") === "production") {
// Serve secure cookies,requires HTTPS
session.cookie.secure = true;
}
如果不是,您需要 npm install express-session
并将 const session = require('express-session');
添加到您的 app.js 的顶部。
我猜你已经知道了,我只是想确定一下。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。