How to post to facebook serverside with Node.js - facebook

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

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

Related

Sharepoint list item using Api Rest

I need to get a list's items, so I created this function
export function retrieveSPItems(spToken, alias) {
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
var myHeaders = new Headers({
Accept: "application/json;odata=nometadata",
Authorization: spToken,
});
return fetch(url, {
method: "get",
headers: myHeaders,
}).then((response) => response.json());
}
As a output I get 3000.
when I change the url to
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;
I get an empty list!
PS :
It's work in Postman with no problem
The token is generated by adaljs :
Get Token
authContext.acquireToken(SP_BASE_URL, function (error, token){....})
Adal config
export const adalConfig = {
tenant: CURRENT_TENANT,
clientId: CURRENT_APP_ID,
endpoints: {
api: CURRENT_APP_ID,
graph: GRAPH_BASE_URL,
sharepoint: SP_BASE_URL,
},
cacheLocation: "localStorage",
validateAuthority: true,
};
So I need to know :
what the reason fot this issue?
How can I fix it?
It's too general information, you need debug and figure out the detailed error information.
My test demo:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="Scripts/adal.js"></script>
<script type="text/javascript">
var authContext = null;
var user = null;
(function () {
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'xxx.onmicrosoft.com',
clientId: '9afc37cb-x-x-x-xxx',
postLogoutRedirectUri: window.location.origin,
endpoints: {
graphApiUri: "https://graph.microsoft.com",
sharePointUri: "https://xxx.sharepoint.com/",
},
cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
};
authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
//$errorMessage.html(authContext.getLoginError());
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
//authContext.acquireToken(window.config.clientId, function (error, token) {
// console.log('---');
//})
authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
alert(token);
if (error || !token) {
console.log("ADAL error occurred: " + error);
return;
}
else {
var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";
$.ajax({
type: "GET",
url: listUri,
headers: {
"Authorization": "Bearer " + token,
"accept": "application/json;odata=verbose"
}
}).done(function (response) {
console.log("Successfully fetched list from SharePoint.");
var items = response.d.results;
for (var i = 0; i < items.length; i++) {
console.log(items[i].Title);
$("#SharePoint").append("<li>" + items[i].Title + "</li>");
}
}).fail(function () {
console.log("Fetching list from SharePoint failed.");
})
}
})
}());
</script>

HTTP 400 on IBM Cloud (Cloud Foundry) with Node.js an Express

I have a simple app with two routes, which I use locally and on IBM Cloud/Cloud Foundry (512 M RAM)
/
returns "Hello World!" & 200 locally and on the IBM Cloud
/getData
returns some data locally & 200
on cloud it returns 400, no logs
Edit:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var cors = require("cors"); // Cors
app.use(cors());
var port = process.env.PORT || 3000;
app.get('/', (req, res) => res.send('Hello World!'))
// *************** GETDATA ***************************************
app.get('/getData', function (req, res) {
var request = require("request");
var httpHeaderOptions = {
accept: "application/json",
"content-type": "application/json",
apikey: req.headers.apikey
};
var restoptions = {
method: "GET",
url: req.headers.route,
headers: httpHeaderOptions
};
// console.log("headers: " + JSON.stringify(req.headers));
// console.log("GET DOCS: \n", JSON.stringify(restoptions));
request(restoptions, function (error, response, body) {
console.log(typeof (body));
body_json = JSON.parse(body);
if (error) {
console.error("Failed: %s", error.message);
body = {
"error": error.message
};
res.status(400).json(body);
} else {
console.log("Success: \n", body);
res.status(200).json(body_json);
}
});
});
// *************** POST DOC ***************************************
app.post('/postData', function (req, res) {
var request = require("request");
var httpHeaderOptions = {
accept: "application/json",
"content-type": "application/json",
apikey: req.headers.apikey
};
var restoptions = {
method: "POST",
url: req.headers.route,
headers: httpHeaderOptions,
body: req.body,
json: true
};
console.log("headers: " + JSON.stringify(req.headers));
console.log("POST DOC: \n", JSON.stringify(restoptions));
request(restoptions, function (error, response, body) {
if (typeof (body) == 'object' && Object.keys(body).length === 0) {
// unknown error, empty resposne
res.status(400).json(body);
} else {
console.log("body: " + JSON.stringify(body));
if (error) {
console.error("Failed: %s", error.message);
body = {
"error": error.message
};
res.status(400).json(body);
} else {
console.log("Success: \n", JSON.stringify(body));
res.status(200).json(body);
}
}
});
});
// *********************
app.post('/watsonAssistant', function (req, res) {
var request = require("request");
var reqURL = "https://hackathon-jps.eu-de.mybluemix.net/watsonAssistant";
console.log("URL: \n", reqURL);
console.log("POST Body: \n", JSON.stringify(req.body));
var httpHeaderOptions = {
accept: "application/json",
"content-type": "application/json",
};
var restoptions = {
method: "POST",
url: reqURL,
headers: httpHeaderOptions,
body: req.body,
json: true
};
console.log("send request \n");
request(restoptions, function (error, response, body) {
console.log("in request \n");
if (error) {
console.error("Failed: %s", error.message);
body = {
"error": error.message
};
res.status(400).json(body);
} else {
console.log("Success: \n", body[0]);
res.status(200).json(body[0]);
}
});
});
// Start the server
app.listen(port, function () {
console.log('simple forward server is running')
});
link to the code
This will be because whatever req.headers.route is set to, is not visible to the app when it is running in the cloud. Your first check should be on error. Your second check should be if body is not null, and an object instead you immediately JSON.parse body, which may be throwing a parsing exception.

i want to download all the reports from service now from api without mentioning the report_id?

https://instance.service-now.com/sys_report_template.do?CSV&jvar_report_id=xxxxx
This URL will only download report for which id is mentioned without mentioning the report_id how can i get all the reports?
This is some rough nodejs code, but should get you started;
var https = require('https');
var username = '';
var password = '';
var url = 'dev32369.service-now.com';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
https.request({
host: url,
port: 443,
path: '/api/now/table/sys_report?sysparm_query=field_listISNOTEMPTY&sysparm_fields=sys_id,title,filter,field,table,field_list&sysparm_limit=2',
method: 'GET',
headers: {
'Authorization': auth,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}, function (reportResponse) {
console.log('STATUS: ' + reportResponse.statusCode);
// console.log('HEADERS: ' + JSON.stringify(res.headers));
var reportResponseBody = '';
reportResponse.setEncoding('utf8');
reportResponse.on('data', function (chunk) {
reportResponseBody += chunk;
// console.log('BODY: ' + chunk);
});
reportResponse.on('end', function () {
var reports = JSON.parse(reportResponseBody).result;
console.log(reports);
if (reports[0].field_list != '') {
for (var x = 0; x < reports.length; x++) {
var report = reports[x];
var path = '';
path += '/api/now/table/' + report.table;
path += '?sysparm_fields=' + report.field_list;
path += '&sysparm_query=' + encodeURIComponent(report.filter);
path += '&sysparm_display_value=true';
path += '&sysparm_exclude_reference_link=true';
// path += '&sysparm_limit=2';
console.log(path);
var optionsCSV = {
host: url,
port: 443,
path: path,
method: 'GET',
headers: {
'Authorization': auth,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
console.log(optionsCSV);
https.request(optionsCSV, function (csvResponse) {
try {
var csvResponseBody = '';
csvResponse.on('data', function (chunk) {
console.log('downloading report[' + report.title + ']...');
csvResponseBody += chunk;
});
csvResponse.on('end', function () {
//console.log(csvResponseBody);
var csvResponseObj = JSON.parse(csvResponseBody).result;
console.log(csvResponseObj);
//this is a json obj but you can rewriet is csv here
});
csvResponse.on('error', function (err) {
console.log(err);
});
} catch (e) {
console.log(e);
}
}).end();
}
}
});
}).end();

Facebook authentication with nodejs

I'm trying to authenticate user in facebook:
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');
getCookies(function(cookies){
logIn(cookies);
});
function logIn(cookies) {
var post_data = querystring.stringify({
'email': 'email#domain',
'pass': 'password'
});
var post_options = {
host: 'www.facebook.com',
port: '80',
path: '/login.php?login_attempt=1',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length,
'user-agent': 'Mozilla/5.0',
'set-cookie': cookies[0]
}
};
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
console.log(res.statusCode);
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
fs.writeFile("C:\\Users\\user\\Desktop\\fb.html", data, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
});
post_req.write(post_data);
post_req.end();
}
function getCookies(callback){
var get_options = {
host: 'www.facebook.com',
port: '80',
path: '/',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'user-agent': 'Mozilla/5.0'
}
};
var get_req = http.request(get_options, function(res) {
var cookies = res.headers['set-cookie'];
res.on('end', function (chunk) {
callback(cookies);
});
});
get_req.write('');
get_req.end();
}
But the response is that cookies in my browser are not enabled. Please don't suggest using existing libraries for connecting to facebook, I'm learning... Thanks for help in advance
Facebook uses OAuth authentication to authenticate an user. I have used oAuth module to get access to the Linkedin APIs at http://nabaruns.blogspot.in/2013/01/linkedin-api-call-using-nodejs-oauth.html. You can try the same and see if you can call graph facebook apis.
Hope this helps

How to send facebook api batch request with node.js

How do I send facebook api batch request with node.js?
FB's examples do not work.
but I finally got danwong/restler.js to work like this:
exports.updateUserFriends = function (userData, next) {
var TOKEN = userData[1];
var fbID = userData[3].id;
var batchreq = {};
batchreq.batch = [];
batchreq.batch.push({"method":"GET", "relative_url":fbID+"/"});
batchreq.batch.push({"method": "GET", "relative_url":fbID+"/friends?limit=50"});
restler.post('https://graph.facebook.com?access_token='+TOKEN,
{data:"batch="+JSON.stringify(batchreq.batch)})
.on('complete', function(data) {
console.log(data);
return next;
});
};
So I thought I'd post this to save someone else a bit of frustration.
First thing to note is that, "Only POST is allowed for batch requests" in FB Api.
var https = require('https');
var url = '/?access_token='+ YOUR_ACCESS_TOKEN_HERE,
batch=[{
"method":"GET",
"relative_url":page + "/insights"
}, {
"method": "GET",
"relative_url":page
}];
url = url + '&batch=' + JSON.stringify(batch);
console.log(url);
var options = {
host:'graph.facebook.com',
path:url,
method: 'POST'
};
var req =https.request(options, function(res){
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
var body='';
res.on('data', function(chunk){
// console.log("body:" + chunk);
body += chunk;
});
res.on('end', function(){
var fbRes = JSON.parse(body);
console.log(fbRes);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();