0

I'm wondering why req.session.username is undefined in the tag >>>DOESNT WORK<<< while it does work in the tag >>>THIS DOES WORK<<< . I brought in req as an argument to my module but it seems I'm supposed to do something else? The /ajax route is accessed via a ajax call and it does set the session variable in >>>THIS DOES WORK<<<


//index.js file

var express = require('express');
var router = express.Router();

var app = express();

var functions = require('../public/javascripts/functions.js');

router.post('/ajax', function(req, res , next){

    var username = req.param("username");
    var password = req.param("password");
    var operation = req.param("operation");

    else if (operation === "validate")
    {




        async.series([

            function()
            {

                functions.validate(username, password, req);

            }

        ], function(err,result)
        {

            if (err)
                return console.log(err);

            console.log(result);

        });
        //req.session.username = "yaryar"; >>>THIS DOES WORK<<<

    }

    var strings = ["rad", "bla", "ska"]

    console.log('body: ' + JSON.stringify(req.body));
    console.log("AJAX RECEIVED");
    res.send(strings);
});

module.exports = router;

functions.js file:

module.exports = {

    validate: function(username, password, req) {

        var url = 'mongodb://localhost';
        var MongoClient = require('mongodb').MongoClient;
        var assert = require('assert');
        var ObjectId = require('mongodb').ObjectID;

        MongoClient.connect(url, function(err, db)
        {
            assert.equal(null, err);
            console.log("Connected correctly to server.");

            var cursor = db.collection('users').find({username : username});

            cursor.each(function(err,doc,req)
            {

                assert.equal(err, null);

                if (doc != null)
                {
                        console.log("user found: " + doc.username);

                                req.session.username = "ttyy"; // >>>DOESNT WORK<<<
                                return true

                }
                else
                {
                        console.log("user not found");
                        return false;
                }
            });
                //db.close();
        });
    }     
};

1 Answers1

0

you're overwriting req by doing cursor.each(function(err,doc,req) change it to cursor.each(function(err,doc,arr) and it will work

pizzarob
  • 11,711
  • 6
  • 48
  • 69