我正在为我的项目实施登录系统。该项目分为两部分:OUTBOUND
中的服务器部分和NodeJS
中的客户端部分。两者都包装在docker容器中,其中包括用于ReactJS
和mySQL
的更多容器。到目前为止,我已经能够连接到PHPMyAdmin
容器中的数据库并将其插入到mySQL
的表中。现在,我尝试使用一个用户登录,如果登录成功,则保存此用户信息,并在询问时返回会话。因此,我在前端调用登录get请求,如下所示:
Users
然后在服务器中,我收到并使用以下信息:
export function signIn(table, userName, password) {
return axios.get(`http://localhost:8000/signin`, {
params: {
table,
userName,
password,
},
}, {withCredentials: true}).then((response) => {
if (response.data.length === 1) {
return "success";
}
return response;
});
}
然后,我希望通过另一个请求来调用它以获取信息并用于修改前端组件的状态,如下所示(这两个请求都在同一文件中):
const bcrypt = require('bcryptjs');
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const multer = require('multer');
const mysql = require('mysql');
const nodeMailer = require('nodemailer');
const session = require('express-session');
const smtpTransport = require('nodemailer-smtp-transport');
const app = express();
const upload = multer();
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 7 * 24 * 60 * 60 * 1000,
secure: false,
}
}));
app.use(cors(({
credentials: true,
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const pool = mysql.createPool({
host: process.env.MYSQL_HOST_IP,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
});
app.get('/signin', (req, res) => {
const { table, userName, password } = req.query;
pool.query(`select * from ${table} where username = '${userName}'`, (err, results) => {
if (err) {
res.send(err);
} else {
if (bcrypt.compareSync(password, results[0].password)) {
req.session.userId = results[0].id;
req.session.name = results[0].name;
req.session.email = results[0].email;
req.session.sex = results[0].sex;
req.session.img = results[0].img;
req.session.userName = results[0].username;
req.session.about = results[0].about;
req.session.save(err => console.log(err));
res.send(results);
} else {
res.send([]);
}
}
});
});
,组件会这样调用它:
app.get('/loggeduser', (req, res) => {
if (req.session.userId) {
const {
userId,
name,
email,
sex,
img,
userName,
about,
} = req.session;
const userInfo = {
userId,
name,
email,
sex,
img,
userName,
about,
};
res.send(userInfo);
} else {
res.send({});
}
});
但是信息永远不会被发回,因为export function getLoggedUser(setUserInfo) {
axios.get(`http://localhost:8000/loggeduser`, {}, {withCredentials: true}).then((response) => {
setUserInfo(response.data);
});
}
始终是req.session.userId
。我尝试添加undefined
到输出console.log
,并且每当刷新页面时(组件调用req.session
时),服务器映像输出的getLoggedUser
的创建时间为从刷新页面的几秒钟前开始,这意味着刷新时会重新创建该页面。是不是由于req.session
而不是get
的请求而无法正确保存?请让我知道我是否可能无法正常工作。