HiDd3N
HiDd3N

Reputation: 494

store data from get method in some object to use afterward

i use express for chat application that i want to write.the problem is when i get data back with get method of express i cant use it in other part of my code and undefined var message in console.log.

code is

// routing
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
  var cookieManager = new co.cookie(req.headers.cookie);

  var client = new memcache.Client(11211, "localhost");
  client.connect();

    user = client.get("sessions/"+cookieManager.get("sec_session_id"), function(error, result){
            var session = JSON.parse(result);
            user = JSON.parse(session.name);
            user = user.username;
    });

});

i want to store user variable and use it in another part of my code so i write console.log(user) after this code but user is undefinde in console.log

any kind of help will be appreciated.

Upvotes: 0

Views: 113

Answers (1)

Chris
Chris

Reputation: 4225

write a function and pass the username like this:

// routing
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
  var cookieManager = new co.cookie(req.headers.cookie);

  var client = new memcache.Client(11211, "localhost");
  client.connect();

  client.get("sessions/"+cookieManager.get("sec_session_id"), function(error, result){
    var session = JSON.parse(result);
    // user = JSON.parse(session.name); // what are you trying to do here?
    // user = user.username;
    do_something_with_user(session.name.username);
  });
});

function do_something_with_user(username) {
  console.log(username);
}

I suggest you check out some tutorials on javascript/node.js like http://www.nodebeginner.org/

Upvotes: 1

Related Questions