hyprstack
hyprstack

Reputation: 4228

nodejs http request returns `undefined`

While trying to debug the following get request, I notice that it returns undefined and then runs the code for the response.

configs is a json object with all the parameters defined. I am also, for some reason, getting a response form the php server saying that grant-type is invalid or can't be found, although when debugging it is passing the correct parameter from the configs file.

How can I correct my code?

var http = require("http");
var querystring = require("querystring");
var _ = require("underscore");

apiCaller = {};

apiCaller.token = null;

var server=http.createServer(function(req,res){});

server.listen(8080);

apiCaller._get = function (context, config, fn) {

    // request to obtain our oauth token
    var options = {
        method: "GET",
        hostname: config.host,
        client_id: config.clientId,
        client_secret: config.clientSecret,
        grant_type: config.grant_type,
        path: "/my/path/to/token",
        headers : {
            'Content-Type': "application/json",
            'Accept': "application/json"
        }
    };

    var callback = function(response) {
        console.log('STATUS: ' + response.statusCode);
        console.log('HEADERS: ' + JSON.stringify(response.headers));
        var str = '';

        //another chunk of data has been recieved, so append it to `str`
        response.on('data', function (chunk) {
            str += chunk;
        });

        // error response
        response.on("error", function (error) {
            if ( !context ) {
                console.error("Something went wrong with the api response.");
                return;
            }
            context.done(new Error("Something went wrong with the api response."));
        });

        //the whole response has been recieved, so we just print it out here
        response.on('end', function () {

            apiCaller.token = JSON.parse(str).access_token;
            // we want to stop the request if token is not correct
            if ( !apiCaller.token || apiCaller.token === undefined || apiCaller.token === null ) {
                if ( !context ) {
                    console.error("Something went wrong with the token. Wrong token! Token: %s", apiCaller.token);
                    return;
                }
                console.error("Token: %s", apiCaller.token);
                context.done(new Error("Something went wrong with the token. Wrong token!"));
            }

        });
    };

    var request = http.request(options, callback);

    request.on('error', function(e) {
        console.log('problem with request:');
    });
    request.end();
};

Upvotes: 0

Views: 4914

Answers (2)

Pedro Perquez
Pedro Perquez

Reputation: 13

As Trott says, It's asynchronous, it's possible that request.end() is executing before callback function has finished....

Upvotes: 0

Trott
Trott

Reputation: 70075

It is an asynchronous function. Asynchronous functions (which are kind of the bread-and-butter of Node.js) typically return nothing. Instead, what you might think of as the return value is passed to the callback function. That's what's happening here.

Upvotes: 1

Related Questions