【问题标题】:in node.js with express req.session is undefined inside my require() module在 node.js 中,在我的 require() 模块中未定义 express req.session
【发布时间】:2016-07-08 15:02:10
【问题描述】:

我想知道为什么 req.session.username 在标签中未定义 >>>DOESNT WORK>>THIS DOES WORK>>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 文件:

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();
        });
    }     
};

【问题讨论】:

    标签: javascript node.js express express-session


    【解决方案1】:

    您通过将cursor.each(function(err,doc,req) 更改为cursor.each(function(err,doc,arr) 来覆盖req,它会起作用

    【讨论】:

      猜你喜欢
      • 2014-04-24
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多