我正在做一个学校项目,无法发送会话数据,因此 我的app.js路由知道该用户可以进入各个站点。
我的第一个想法是在批准登录信息后将其发送并重定向到Auth.js中的首页,但我不知道如何发送,以便我的首页路由可以通过checkAuth函数查看并处理它。
我的另一个想法是使用users.js中所示的几个“设置/获取”路由。但是无法弄清楚我将如何进一步实现这一点。
我不知道哪种方式最适合此类应用程序。
这是负责登录的Auth.js:
const router = require('express').Router();
const User = require("../models/User.js");
const bcrypt = require('bcrypt');
const saltRounds = 12;
router.post('/login', (req, res) => {
// get request from body
const { username, password } = req.body;
//console.log(req.body);
// ask if this is a username with a password
if (username && password) {
// goes through db to see if username exists
User.query().select('username').where('username', username).then(foundUsername => {
try {
if (foundUsername[0].username == username) {
console.log(foundUsername[0].username);
User.query().select("password").where('username', foundUsername[0].username).then(foundPassword => {
console.log(foundPassword[0].password);
bcrypt.compare(password, foundPassword[0].password).then(result => {
console.log(result)
if (result == true) {
// this is where i want to set the req.session.user_id = true;
// and send it to my /frontpage
return res.redirect("/frontpage");
} else {
return res.status(400).send({ response: "wrong username or password" });
};
});
});
} else {
return res.status(400).send({ response: "wrong username or password" });
};
} catch (error) {
return res.status(400).send({ response: "wrong username or password" });
};
});
};
});
module.exports = router;
这是我的app.js,它检查传入请求中的req.session.user_id
function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.send('You are not authorized to view this page');
} else {
next();
}
}
app.get("/frontpage", checkAuth, (req, res) => {
console.log(req.body);
return res.sendFile(__dirname + "/public/frontpage.html");
});
这是我的users.js。这是我想到的获取和设置会话值的另一种方式:
router.get('/setsessionvalue', (req, res) => {
req.session.user_id = true;
return res.send({ response: "OK" });
});
router.get('/getsessionvalue', (req, res) => {
return res.send({ response: req.session.user_id });
});