aCuria
aCuria

Reputation: 7175

How to post to facebook serverside with Node.js

As per the question title, I am trying to post to facebook serverside with node.js Unfortunately there is something wrong with how I am doing it... I am getting the error

{ [Error: socket hang up] code: 'ECONNRESET' }

app.post('/post/:id?', function(req, res)
{
var id = req.route.params.id;
var token = tokens[id].token;
var path = '/' + id + '/feed?access_token=' + token;
var message = "server side post to facebook";

console.log("post.id = " + req.route.params.id);

var jsonobject = JSON.stringify(
{
    'message'   :   message
});

var options = {
    host: 'graph.facebook.com',
    port: 443,
    path: path,
    method: 'post',
    headers: {
      'content-type': 'application/json',
      'content-length': jsonobject.length()
    }
};

var req = https.request(options, function(res) {
    console.log("statuscode: ", res.statuscode);
    console.log("headers: ", res.headers);
    res.setencoding('utf8');
    res.on('data', function(d) {
        process.stdout.write(d);
    });
    res.on('end', function(){ // see http nodejs documentation to see end
        console.log("finished posting message");
    });
});

req.on('error', function(e) {
    console.error(e);
});

req.write(jsonobject);
req.end();
});

Upvotes: 1

Views: 1637

Answers (1)

aCuria
aCuria

Reputation: 7175

I am not sure exactly what I did, but after lots of hacking it seems to work... So for anyone who is interested:

app.post('/post/:id?', function(req, res)
{
var id = req.route.params.id;
var token = tokens[id].token;
var path = '/' + id + '/feed?access_token=' + token;
var strToPost = "server side post to facebook";

console.log("post.id = " + req.route.params.id);

var post_data = querystring.stringify({
    'message' : 'testing server side post'
});

var options = {
    host: 'graph.facebook.com',
    port: 443,
    path: path,
    method: 'POST',
    headers: {
      'Content-Type'    : 'application/x-www-form-urlencoded',
      'Content-Length'  : post_data.length
    }
};

var req = https.request(options, function(res) {
    console.log("statuscode: ", res.statuscode);
    console.log("headers: ", res.headers);
    res.setEncoding('utf8');
    res.on('data', function(d) {
        console.log("res.on data");
        process.stdout.write(d);
    });
    res.on('end', function(){ // see http nodejs documentation to see end
        console.log("\nfinished posting message");
    });
});

req.on('error', function(e) {
    console.log("\nProblem with facebook post request");
    console.error(e);
});

req.write(post_data);
req.end();
});

Upvotes: 4

Related Questions