Taking data from graph api with node - node.js

I am trying to connect with the facebook api to be able to get a feed of a certain page.
But I'm getting an access token error
{"error":{"message":"Invalid OAuth access token.","type":"OAuthException","code":190,"fbtrace_id":"DrEySZsEOOA"}}
I'm trying this:
Facebook.js:
var https = require('https');
exports.get = function(accessToken, apiPath, callback) {
var options = {
host: 'graph.facebook.com',
port: 443,
path: apiPath + '?access_token=' + accessToken,
method: 'GET'
};
var buffer = '';
var request = https.get(options, function(result){
result.setEncoding('utf8');
result.on('data', function(chunk){
buffer += chunk;
});
result.on('end', function(){
callback(buffer);
});
});
request.on('error', function(e){
console.log('error from facebook.get(): '
+ e.message);
});
request.end();
}
app.js:
var facebook = require('./facebook');
var http = require('http');
var server = http.createServer(app);
facebook.get('121212', '/feed/', function(data){
console.log(data);
});
server.listen(9999);
Yes, I passed the right token. I just modified it for obvious reasons hahaha
Would anyone have an idea or an example?
Thank you all

This would be the API call: https://graph.facebook.com/feed?access_token=xxx
...which is missing something important: the ID of a User, Page or Group.
For example: https://graph.facebook.com/[page-id]/feed?access_token=xxx
Keep in mind that you need different Tokens and permissions if it is about a User, Page or Group.

Related

Error: connect ECONNREFUSED. Unhandled 'error' event NodeJS

I am encountering the Nodejs error ECONNREFUSED 127.0.0.1:3000 when I try to send a get request to load a static file. I have seen many questions on this error but apparently there is no straight answer as to why this error is thrown. Here below is the code I have. I have tried changing localhost to 127.0.0.1 or change port numbers 3000, 7000, 8080 but nothing resolved it. Can someone please advised? Thank you.
//Basic web client retrieving content of file using get request
var http = require('http');
//options for request
var options = {
hostname: 'localhost',
port: '3000',
path: '../html/hello.html'
};
//function to handle response from request
function getResponse(response){
var serverData='';
response.on('data', function(chunk){
serverData += chunk;
});
response.on('end', function(){
console.log(serverData);
});
};
http.request(options, function(response, error){
getResponse(response);
}).end();
Your client code is good enough to work. You are getting the ECONNREFUSED because there is a no server which is listening to the particular port number and the Server is not sending any data and you are requesting to get data from the server and accumulate it.
Here is the sample code:
//Requesting for http and fs modules
var http = require('http');
var fs = require('fs');
//creating the server and reading the file synchronously
var server = http.createServer(function(req, res) {
res.end(fs.readFileSync('./html1.html'));
}).listen(3000);
//creating the client which connects to local host at port number 3000
var options = {
hostname: 'localhost',
port: '3000',
}
//getting the data from server, storing it in to a variable, and printing at end of the data
function getResponse(response){
var serverData='';
response.on('data', function(chunk){
serverData += chunk;
});
response.on('end', function(){
console.log(serverData);
});
};
http.request(options, function(response, error){
getResponse(response);
}).end();
the issue in your code , that you are not handling error, for this you have to handle error first.
var http = require('http');
var options = {
hostname: 'localhost',
port: '3000',
path: '../html/hello.html'
};
function getResponse(response){
var serverData='';
response.on('data', function(chunk){
serverData += chunk;
});
response.on('end', function(){
console.log(serverData);
});
};
http.request(options, function(error , response){
if(error){
console.log(error);//handle error here.
}else{
getResponse(response);
}}).end();

testing local https server with mocha/superagent

So I see there was a pull request a few months ago for superagent to allow you to specify the CA in a request. It does not appear that the docs were updated to reflect this change, so I can't seem to figure out how to do it.
I am trying to test on my local machine a REST service which exposes both http and https endpoints. All the http ones work fine, the SSL ones....well.....not so much.
After spending all day yesterday running down certificate errors, I am 90% certain I have the server working correctly. Curl seems to think so, as does a vanilla node request object.
I assume superagent is probably creating a request under the hood - I just need to know how to pass in the CA for it.
Thanks in advance.
There is a usage example in their tests.
Basically:
var https = require('https'),
fs = require('fs'),
key = fs.readFileSync(__dirname + 'key.pem'),
cert = fs.readFileSync(__dirname + 'cert.pem'),
assert = require('better-assert'),
express = require('express'),
app = express();
app.get('/', function(req, res) {
res.send('Safe and secure!');
});
var server = https.createServer({
key: key,
cert: cert
}, app);
server.listen(8443);
describe('request', function() {
it('should give a good response', function(done) {
request
.get('https://localhost:8443/')
.ca(cert)
.end(function(res) {
assert(res.ok);
assert('Safe and secure!' === res.text);
done();
});
});
});
This worked for me:
...
var user = request.agent({ca: cert});
...
Full example:
var expect = require('chai').expect;
var should = require('should');
var request= require('superagent');
var fs = require('fs');
var cert = fs.readFileSync('sslcert/server.crt', 'utf8');
var validUser = { username: 'test#test.com', password: 'secret111' };
describe('User', function() {
// provide certificate as agent parameter
var user = request.agent({ca: cert});
it("/login", function(done) {
user
.get('https://localhost:3000/login')
.end(function(err, res) {
if(err) throw err;
// HTTP status should be 200
res.status.should.equal(200);
user
.post('https://localhost:3000/login')
.send(validUser)
.end(function(err, res) {
if(err) throw err;
// HTTP status should be 200
res.status.should.equal(200);
done();
// user will manage its own cookies
// res.redirects contains an Array of redirects
});
});
});
it("/", function(done) {
user
.get('https://localhost:3000/')
.end(function(err, res) {
if(err) throw err;
// HTTP status should be 200
res.status.should.equal(200);
done();
});
});
it("/logout", function(done) {
user
.get('https://localhost:3000/logout')
.end(function(err, res) {
if(err) throw err;
// HTTP status should be 200
res.status.should.equal(200);
done();
});
});
});

Get url and body from IncomingMessage?

I am very new to node. I am at the point at which I have a simple server which should just print the request query and the request body which it takes. What I've understood is that the "handle request" function actually doesn't return a request object, rather an IncomingMessage object.
There are two things which I don't understand: How to obtain the query string and the body.
I get just the path, without the query and undefined for the body.
Server Code:
var http = require('http');
var server = http.createServer(function (request, response) {
console.log("Request query " + request.url);
console.log("Request body " + request.body);
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("<h1>Hello world!</h1>");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
Request code:
var http = require('http');
var options = {
host: '127.0.0.1',
port: 8000,
path: '/',
query: "argument=narnia",
method: 'GET'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('response: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write("<h1>Hello!</h1>");
req.end();
Please note that I am a complete beginner. I am not looking for express only solutions.
The reason that you do not see the query string at request.url is that you aren't sending one correctly. In your request code, there is no query property of options. You must append your querystring to the path.
path: '/' + '?' + querystring.stringify({argument: 'narnia'}),
For your second question, if you want the full request body, you must read from the request object like a stream.
var server = http.createServer(function (request, response) {
request.on('data', function (chunk) {
// Do something with `chunk` here
});
});

NodeJS: How to save facebook profile picture

I am using express and nodejs and am having problems saving facebook profile pictures to my server.
Location of picture: http://profile.ak.fbcdn.net/hprofile-ak-ash2/275619_223605264_963427746_n.jpg
Script Being Used:
var http = require('http')
var fs = require('fs')
var options = {
host: 'http://profile.ak.fbcdn.net',
port: 80,
path: '/hprofile-ak-ash2/275619_223605264_963427746_n.jpg'
}
var request = http.get(options, function(res){
res.setEncoding('binary')
var imagedata = ''
res.on('data', function (chunk) {imagedata += chunk})
res.on('end', function(){
fs.writeFile('logo.jpg', imagedata, 'binary', function (err) {
if(err){throw err}
console.log('It\'s saved!');
})
})
})
The image saves but is empty. Console logging the image data is blank too. I followed this example origionally which does work for me. Just changing the location of the image to the facebook pic breaks the script.
I ended up coming up with a function that worked:
var http = require('http');
var fs = require('fs');
var url = require('url');
var getImg = function(o, cb){
var port = o.port || 80,
url = url.parse(o.url);
var options = {
host: url.hostname,
port: port,
path: url.pathname
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
res.setEncoding('binary')
var imagedata = ''
res.on('data', function(chunk){
imagedata+= chunk;
});
res.on('end', function(){
fs.writeFile(o.dest, imagedata, 'binary', cb);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}
USAGE:
getImg({
url: "http://UrlToImage.com",
dest: __dirname + '/your/path/to/save/imageName.jpg'
},function(err){
console.log('image saved!')
})
I know my answer is a little late, but I hope it'll help others we get to this question, so here it is:
Saving the file to the root directory of your Node server can be done this way:
var request = require("request");
var fs = require("fs");
var fbUserId = 4;
var imageLink = "https://graph.facebook.com/"+ fbUserId +"/picture?width=500&height=500";
request(imageLink).pipe(fs.createWriteStream("resultIMG.png"))
.on('close', function(){
console.log("saving process is done!");
});
Of course, you can add any path you want for the image prior the the file name string.
If you still are seeing empty images, set the encoding of the request module to null , like this:
var request = require("request").defaults({ encoding: null });
That should do it.

Difficulties with node.js proxy

I am attempting to make a GET request for a single image on another server from node.js.
var http = require('http');
var site = http.createClient(80, '192.168.111.190');
var proxy_request = site.request('/image.png');
proxy_request.on('response', function (proxy_response) {
console.log('receiving response');
proxy_response.on('data', function (chunk) {
});
proxy_response.on('end', function () {
console.log('done');
});
});
And even with this code, I can't get the "receiving response" message to print out. Outside of node, I can do a curl http://192.168.111.190/image.png just fine, but is there something else I might be missing?
for get requests try the http.get API http://nodejs.org/docs/v0.4.9/api/http.html#http.get
var http = require('http');
var options = {
host: '192.168.111.190',
port: 80,
path: '/image.png'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});

Resources