Hadesara
Hadesara

Reputation: 159

express session management not working

I am new to the node.js world. I am trying to write a REST services and I am stuck with session management. So I created a separate app just to see if I can get the session to work, but it doesn't, here is the code. The req.session.username is always undefined:

var express = require('express');
var url = require('url');

var app = express()
app.use(express.cookieParser('Hiren'))
app.use(express.session({ secret: 'HirenAdesara' }))
app.use(express.bodyParser())
app.use(app.router)

//Sniff HTTP
app.all('*', function(req, res, next) {
    //Check for Authentication
            console.log(req.session)
    if ((!(/^\/auth/g.test(req.url))) && (!req.session)) {
        console.log('in app.all: Unauthorized')
        res.send(401)
    }
    else
    {
        return next()
    }
})

app.post('/auth', function(req, res) {
                var query =  req.body
                console.log('Query' + JSON.stringify(query))
                username = query.username;
                password = query.password;
                if(username == 'Hiren' && password == 'Adesara')
                {
                    req.session.username = 'Hiren';
                    console.log('New Session Created..')
                    res.send(200)
                }
                else
                {
                    console.log('New session could not be created.')
                    res.send(401)
                }
})

app.get('/projects', function(req,res) {
    console.log('inside projects' + req.session.username);
    res.send(req.session.username); })

app.listen(2048)
console.log('Listening on port 2048...')

It doesn't work and I have no idea what is wrong here.

Upvotes: 0

Views: 3158

Answers (1)

Hector Correa
Hector Correa

Reputation: 26690

Star by moving the 3 lines in your app.get('/'...) outside of it:

var express = require('express');
var querystring = require('querystring');

var app = express()
app.use(express.cookieParser('Hiren'));   // This line
app.use(express.session({ secret: 'HirenAdesara' })); // This line
app.use(express.bodyParser()); // This line

app.get('/', function(req, res){
   res.send('hello from the root page');
})

// the rest of your code

Upvotes: 3

Related Questions