访问服务器端会话变量reactjs / expressjs

发布于 2025-02-08 13:13:12 字数 768 浏览 0 评论 0原文

我正在使用Express作为后端编写一个简单的CRUD,并作为前端进行反应。在后端,在正确登录了用户后,我创建了一个会话变量,在其中存储了有关用户的信息 - 它运行良好。

在前端的某些地方,我想知道用户是否经过身份验证(如果设置session.user,请在服务器会话中检查)。

这是在前端验证用户身份验证的适当方法吗?还是有更好的方法可以在前端验证用户的身份验证?

这是我设置会话变量的代码:

    module.exports = {
    login: function(req, res){

        const {email, password} = req.body;

        console.log(email, password);

        UserModel.authenticate(email, password, function(err, result){
            if(err){
                throw err;
            }

            if (result.rows.length == 0){
                return res.status(404).send('Bad credentials');
            }

            req.session.user = result.rows[0];

            return res.sendStatus(200);

        });
    }
}

I'm writing a simple CRUD with login app using Express as a backend and React as a frontend. In the backend, after user is logged in correctly, I create a session variable, where I store information about the user - and it works well.

In some places in the frontend, I want to know if user is authenticated or not (checking in the server session if session.user is set).

Is this a proper approach of verifying user's authentication in the frontend? Or is there a better way of verifying user's authentication in the frontend?

Here's my code where I'm setting session variable:

    module.exports = {
    login: function(req, res){

        const {email, password} = req.body;

        console.log(email, password);

        UserModel.authenticate(email, password, function(err, result){
            if(err){
                throw err;
            }

            if (result.rows.length == 0){
                return res.status(404).send('Bad credentials');
            }

            req.session.user = result.rows[0];

            return res.sendStatus(200);

        });
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文