Hick
Hick

Reputation: 36384

How to return a value from a callback in nodejs?

This is my index.js

app.get('/api/user', auth.authenticate, function(req, res){
    res.send("hi");
});

This is my auth.authenticate function:

exports.authenticate = function(req, res,done) {
 // function checkToken(req,res,next){
    console.log(req.body);
    authToken = req.body["auth_token"]
    consumerKey = req.body["consumer_key"]
    checkAuth(authToken,consumerKey,function response(user){
      done();
    });
}

After authenticating, I want to return "user" back to the app.get in index.js so that I can use it to retrieve more data but I'm somehow not able to understand how to do that.

Is it possible to send user via the done() callback? I tried it but was unsuccessful.

Upvotes: 0

Views: 61

Answers (1)

AndyD
AndyD

Reputation: 5385

Yes that's possible as the request object passed around in Express.js is the same. Just add it to the request like this:

checkAuth(authToken,consumerKey,function response(user){
  request.user = user;
  done();
});

and then you can use it in the index.js

app.get('/api/user', auth.authenticate, function(req, res){
    res.send("hi " + req.user);
});

Upvotes: 1

Related Questions