简体   繁体   English

如何在Node JS中添加会话

[英]How to add a session in Node js

we're working on a project for our Programming-Course. 我们正在为我们的编程课程开发一个项目。 We're doing a very small social media platform, where you can register, login, create a profile, view events and log out. 我们正在做一个非常小的社交媒体平台,您可以在其中注册,登录,创建个人资料,查看事件并注销。

So I set the session variable for logging in, but I also want that people who register are instantly logged in and get redirected to the profile-site. 因此,我设置了用于登录的会话变量,但我也希望注册人员可以立即登录并重定向到个人资料站点。 So I have to set another session into the registration app.post I guess, but I have absolutly no Idea how to do this (because I'm a bloody beginner)... Can anybody help? 所以我想我必须在注册app.post中设置另一个会话,但是我绝对不知道该怎么做(因为我是个流血的初学者)...有人可以帮忙吗? This is the code so far: 到目前为止,这是代码:

//------------Sessionvariables---------------//
app.get('/', requiresLogin, function(req, res) {
    res.render('home', {
        'username': req.session.user.name
    });
});

app.post('/sendLogin', function(req, res) {
    //in Datenbank gucken
    const user = req.body["username"];
    const password = req.body["password"];
    db.get(`SELECT * FROM users WHERE username='${user}'`, function(err, row) {
        if (row != undefined) {
            if(password == row.password) {
                req.session['user'] = user;
                res.redirect('/home');
            }else{
                res.redirect('/loginerror');
            }
        }else{
            res.redirect('/loginerror');
        }
        if(err){
            console.error(err.message);
        }
    });
});

app.get('/logout', function(req, res){
    req.session.destroy(function (err) {
      if (err) return next(err)
        req.session = null;
      res.redirect('/start-login');
    });
});

// Registration
app.post('/registration', function(req, res) {
    const { email, password, username, domicile } = req.body;
        // validation
    db.run(`INSERT INTO users(email,password,username,domicile) VALUES(?, ?, ?, ?)`, [email, password, username, domicile], function(err) {
         if (err) {
             return console.log(err.message);
         }
         return res.redirect('/edit_profile');
     });
});

I know that I have to write the session into the app.post /registration - Part, but I don't know how to write it. 我知道我必须将会话写入app.post / registration-Part,但是我不知道如何编写。 I'm using Node js, Express and sqlite3... 我正在使用Node js,Express和sqlite3 ...

Thank you!! 谢谢!!

Why not just do: 为什么不做:

// Registration
app.post('/registration', function(req, res) {
    const { email, password, username, domicile } = req.body;
        // validation
    db.run(`INSERT INTO users(email,password,username,domicile) VALUES(?, ?, ?, ?)`, [email, password, username, domicile], function(err) {
         if (err) {
             return console.log(err.message);
         } else {
             // Create the session / save any data you want here
             req.session.user.name = username;
             /* I would actually call somthing like: createSession(req)
                dedicated function that nicely creates the session */
             // Redirect to home just like you do after successful login
             res.redirect('/home'); // Redirect to home since user registered successfully
         }
     });
});

By the way always treat error before running other code logic i see you are treating errors at the end of code (in the app.post('/sendLogin',...) : 顺便说一句,在运行其他代码逻辑之前总是要处理错误,我看到您在代码末尾处理错误(在app.post('/sendLogin',...)

if(err){
  console.error(err.message);
}

Write like this: 这样写:

if(err){
  console.error(err.message);
  // and res.end() or similar if its in an express route
} else {
  // Do safe stuff here
}

我可以建议您的最佳方法是,注册成功后,在会话中设置用户详细信息,然后重定向到您的主页

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM