RafDev RafDev - 6 months ago 11
Javascript Question

HTTP Request in Node.js not working?

I'm trying to make an HTTP Request function. All requests go to the same directory on the same domain, only the file name is different.

Nothing is coming up in the console, and it's not returning anything.

function HttpRequest(filename){

var options = {
host: "example.com",
port: 80,
path: "/path/to/file/" + filename,
method: "GET",
};

var Response = "";
var StatusCode = 0;

var req = http.request(options, function(resp){
resp.on('data', function(data){
Response = data;
StatusCode = resp.statusCode;
});
});

req.on('error',function(e){
console.log("Request to '" + filename + "' failed: " + e.message)
});

req.write('data\n');
req.write('data\n');
req.end();

return Response;
}

Answer

You are running into this issue because the http.request function is inherently asynchronous - you have no idea when it will return, if at all.

This block of code will assign the correct values to the correct variables (though, you might run into an issue with scope here):

var req = http.request(options, function(resp){
        resp.on('data', function(data){
            Response = data;
            StatusCode = resp.statusCode;
        });
    });

but you never quite know when Response is set to data. When you write return Response, you are essentially returning the value of Response as soon as the function finishes executing - but this does not mean that the HTTP request is completed or that the callback has been executed.

As @Jonathan Lonowski mentioned in a comment, this answer is how you should attempt your problem.

Essentially, you need to use a callback that you provide as a parameter to your function.

function HttpRequest(filename, callback){

    var options = {
        host: "example.com",
        port: 80,
        path: "/path/to/file/" + filename,
        method: "GET",
    };

    var req = http.request(options, function(resp){
        resp.on('data', callback);
    });

    req.on('error',function(e){
        console.log("Request to '" + filename + "' failed: " + e.message)
    });

    req.write('data\n');
    req.write('data\n');
    req.end();
}

Then, when calling your function:

HttpRequest("myfile", function(data) {
    console.log(data);
});
Comments