Question

I'm running Node.js on Heroku, and I have a simple test url set up on express to make a client request, but it crashes the application everytime and I'm not sure why.

I'm trying to make the server make a simple GET call to https://graph.facebook.com/btaylor

My related server.js contents:

app.get('/test', function(request, response) {
    var http = require('http');
    var test_client = http.createClient(443, "graph.facebook.com", true);

    var facebook_request = test_client.request("GET", "/btaylor", {
        "host":"graph.facebook.com"
    });

    facebook_request.on('response',function(facebook_response){
        facebook_response.on('data',function(chunk){
            console.log(chunk);
        });
        facebook_response.on('end', function() {
            console.log("DONE");
        });
    });
    facebook_request.end();
});

This looks pretty straight forward, but it crashes the server everytime I visit server/test.

I know I'm hitting the right code, because if I remove for example the line "var http = ...", I'll get a "http not defined" as it tries to run http.createClient.

Was it helpful?

Solution

Use the https module for node.js to connect to https websites. The way you do it is overly complicated for simple requesting data.

var express = require("express");
var app = express.createServer();

app.get('/test', function(request, response) {
    var https = require('https');

    response.writeHead(200);
    https.get({ host: 'graph.facebook.com', path: '/btaylor' }, function (res) {
        console.log(res);
        response.end(res.body);
    });
});

app.listen(process.env.PORT);

You might also consider using request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top