idude
idude

Reputation: 4912

How to use res.send() in Node.js

I am using mongoose api with a Node.js/Express application. I have a get request on the client side that asks for some data, but for some reason that data never makes it to the client side. What is wrong?

Snippet of backend

app.get('/up', isLoggedIn, function(req,res){
    req.user.local.level = 2;
    req.user.save(function(err){
        res.send(req.user.local.level);
    });

});

Snippet of Frontend

function try(){
    var ks=1;
    if(true){
            $.get('/up', function(data){
                ks=data;    
            });
        }
        console.log(ks);
    }

The server console displays 2, yet the browser console still displays 1, What is wrong?

Edit
I took your advice but it still wont work. What am i doing wrong?

var ks=1;
if(true){
    jQuery.ajax({
         url:    '/up' ,
         async:   false,
         success: function(data) {
                    ks = data;
                    console.log(ks);
                  }

    });
    }

Upvotes: 0

Views: 1643

Answers (1)

SLaks
SLaks

Reputation: 887415

    console.log(ks);

That code runs as soon as you send the request, before the response arrives.

Upvotes: 1

Related Questions