我怎样才能强迫Node.js在登录时不显示我的登录按钮,并在注销时显示它



当用户登录时,req.session.loggedin更改为true,所以我希望按钮在变量更改为true时消失/出现。所以简而言之,我想知道如何从Node.js文件中更改pug文件中的loggedin变量。

app.use(function(req, res, exit) {
if(req.session.loggedin) {
app.locals.loggedin = true;
}
else {
app.locals.loggedin = false;
}
res.app.use(express.static(path.join(__dirname, '/site/data')))
exit();
})

这是。pug

- var loggedin = false;
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

如果你有问题,不要害怕问。

所以我可以注意到你的代码中的几个问题:

  1. 你不需要if语句,req.session.loggedin应该已经是布尔值了
  2. 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;
}

如果没有,你需要在app.js的顶部添加npm install express-sessionconst session = require('express-session');

我想你已经拿到了,我只是想确认一下。

最新更新