在带有express req.session的node.js中,我的require()模块中未定义

时间:2016-07-08 05:59:27

标签: javascript node.js express express-session

我想知道为什么标签中的req.session.username未定义>>> DOESNT WORK<<<虽然它确实可以在标签中使用>>>这样做工作<<< 。我带来了req作为我的模块的参数,但似乎我应该做别的事情? / ajax路由是通过ajax调用访问的,它确实在>>>中设置了会话变量。这就是工作<<<<

//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文件:

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 个答案:

答案 0 :(得分:0)

您通过cursor.each(function(err,doc,req)将其更改为cursor.each(function(err,doc,arr)来覆盖请求,并且可以正常工作