我正在尝试让会话与 React 前端和使用 MongoStore 后端的 express + connect-mongo 一起工作。
处理寄存器功能
async function handleRegister(evt){
//Prevent default form redirect.
evt.preventDefault();
//Create a new user objec to pass into axios
const user = {
username: username,
password: password
}
//Send axios post request to nodeJS API.
await axios.post("http://localhost:5000/users/register",user)
.then((res) => {
history.push({
pathname: '/',
state: res.data
});
})
.catch((err) => {
console.log(err);
});
//Push react history back to index page.
}
处理登录功能
const handleLogin = async (evt) => {
//Prevent default form submission
evt.preventDefault();
const loginDetails = {
username: username,
password: password,
}
//send login request to api
await axios.post('http://localhost:5000/users/login', loginDetails)
.then((res) => {
})
.catch((err) => {
})
}
我一直在试图弄清楚如何在上述任何一个功能之后将数据发送回以做出反应。在注册功能中,我发回了res.data包含会话的内容。见快递路线
router.post('/register', async (req, res) => {
//Destructure req.body.
const {username,password} = req.body;
//hash password.
const hashedPassword = await hashPassword(password);
//Create new user to store in mongodb.
const newUser = {
username: username,
password: hashedPassword
}
//Create new user document
await User.create(newUser, (err, newlyAddedUser) => {
if(err){
console.log(err);
}else{
req.session.username = newlyAddedUser.username;
console.log(req.session);
res.send(req.session);
}
})
});
使用console.log(req.session)它输出我在会话本身中添加的cookie和用户名。
我应该在反应端创建一个用户对象并将用户名和密码存储在里面吗?我是否应该将会话本身传递回路由, history.push({ pathname: '/',state: res.data});
如何使用 connect-mongo 验证会话对用户有效?