0

我正在尝试让会话与 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 验证会话对用户有效?

4

1 回答 1

0

我花了 10 分钟试图了解你的目标是什么。没找到。

但是,如果您想验证会话是否有效,如您所说,无论您需要使用 jsonwebtoken

享受https://jwt.io/

https://www.npmjs.com/package/jsonwebtoken

我不会像你那样将会话存储在历史状态 API 中。

       history.push({
           pathname: '/',
           state: res.data
       });

你最好使用 sessionStorage 和/或 localStorage。这个名字只是自言自语。

请给我一分

于 2021-01-03T23:43:09.947 回答