nodejs http请求返回`undefined`

时间:2015-04-21 15:18:57

标签: node.js

在尝试调试以下get请求时,我注意到它返回undefined,然后运行response的代码。

configs是一个json对象,定义了所有参数。出于某种原因,我也是从php服务器获得响应,说grant-type无效或无法找到,尽管在调试时它正在从configs文件中传递正确的参数。

如何更正我的代码?

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

2 个答案:

答案 0 :(得分:0)

这是一个异步功能。异步函数(它们是Node.js的一种优势)通常不会返回任何内容。相反,你可能会想到的返回值被传递给回调函数。这就是这里发生的事情。

答案 1 :(得分:0)

正如Trott所说,它是异步的,在回调函数完成之前,request.end()可能正在执行....