Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Andrew Young
PLUS
Andrew Young
Courses Plus Student 639 Points

How do you clear all data in express session without stopping it?

I write a code something like this

var express = require('express');
var app = express();
var session = require('express-session');
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(session({ secret: makerandstr() }))
//                                        ^^^^^^^^^^^^^^^ this function generate random string
//other node.js setting including fs, body-parser

app.post('/api/v1/login', function(req, res) {
    var users = readdata("users");
    var sess = req.session;
    if (users[req.body.username]) {
        if (users[req.body.username].pwd == req.body.password) {
            req.session.destroy();
            sess.login = true;
            sess.username = req.body.username;
            sess.role = users[req.body.username].role;
            res.redirect(302, '/testsess');
        }
    } else {
        req.session.destroy();
        sess.login = false;
        sess.loginerror = "User authorize failed";
        res.redirect(302, '/login')
    }
});

With the above code I tried to clear the data of previous session using req.session.destroy(); function but it seems like you can't store data after you destroy it.

So how can I clear the data in the session and can store data right after it?