Query multiple SharePoint lists Using REST API and angular JS - rest

I have a scenario of fetching data from multiple SharePoint 2013 lists using REST API and Angularjs. I am able to fetch the data successfully from one of the SharePoint list but my requirements is to fetch the data from multiple lists on the page load. I am using a provider hosted app to fetch the data from host web. I have 2 methods for calling 2 separate lists. I am getting the results from first method successfully but when the second method is called after the execution of 1st method. I am getting a time out error. It seems like i cannot call the 2 methods one after the other. Below is my code, could anyone please help me if i am missing something or if there is any other way to fetch the data from multiple SharePoint lists.
Method 1: fetch Data from List 1
var query = listEndPoint + "/getbytitle('CandidateList')/items?$select=ID,FirstName,MiddleInitial,LastName,EmailAddress,PrimaryPhoneNo,ProfileImage,Address,State,Country,CurrentTitle,CurrentCompany,LastActivityModifiedBy,LastActivityModifiedDate,DeletedStatus&#target='" + hostweburl + "'";
var getCandidates = function (query, queryCandidateNotes)
{
alert('getRequest');
var scriptbase = hostweburl + "/_layouts/15/";
var deferred = $q.defer();
// Load 15hives js files and continue to the successHandler
$.getScript(scriptbase + "SP.Runtime.js",
function () {`enter code here`
$.getScript(scriptbase + "SP.js",
function () {
$.getScript(scriptbase +"SP.RequestExecutor.js",
function () {
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
});
//deferred.resolve();
});
});
});
function successHandler(data) {
var jsonObject1 = JSON.parse(data.body);
deferred.resolve(jsonObject1);
}
function errorHandler(data, errorCode, errorMessage) {
alert('Error1:' + errorMessage + data.body);
}
// Get
return deferred.promise;
//Candidate Details Ends
};
Method 2: fetch Data from List 2
var queryCandidateNotes = listEndPoint + "/getbytitle('CandidateNotes')/items?$select=Title,CandidateId&#target='" + hostweburl + "'";
// Get All Candidate Notes
var getCandidateNotes = function (queryCandidateNotes) {
alert('getCandidateNotesRequest');
var scriptbase = hostweburl + "/_layouts/15/";
var deferred2 = $q.defer();
// Load 15hives js files and continue to the successHandler
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js",
function () {
$.getScript(scriptbase + "SP.RequestExecutor.js",
function () {
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: queryCandidateNotes,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
});
//deferred.resolve();
});
});
});
function successHandler(data) {
var jsonObject2 = JSON.parse(data.body);
//var results2 = jsonObject2.d.results;
deferred2.resolve(jsonObject2);
//alert('2nd success:' + jsonObject2);
//return jsonObject2;
}
function errorHandler(data, errorCode, errorMessage) {
alert('Error2 :' + errorMessage + data.body);
}
// Get
return deferred2.promise;
};
Method 3: Calling method 2 after method 1
var getRequest = function (query, queryCandidateNotes) {
var deferred = $q.defer();
$.when(getCandidates(query, queryCandidateNotes)).then(function (data) {
alert('Success1:' + data);
$.when(getCandidateNotes(queryCandidateNotes)).then(function (data1) {
deferred.resolve(data);
alert('Success2:' + data1);
});
})
return deferred.promise;
};
return {
getRequest: getRequest
};
}]);
})();

$.when is not appropriate here, utilize $q.all that combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
Example
app.controller('listController', function ($scope, $q, listService) {
SP.SOD.executeFunc('SP.RequestExecutor.js', 'SP.RequestExecutor', function () {
$q.all([listService.getListItems('Documents'), listService.getListItems('Site Pages')]).then(function (data) {
$scope.documentsItems = data[0].d.results;
$scope.sitePagesItems = data[1].d.results;
});
});
});
where listService is a service for getting list items:
app.factory('listService', ['$q', function ($q) {
var getListItems = function (listTitle) {
var d = $q.defer();
JSRequest.EnsureSetup();
var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
var appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]);
var queryUrl = appweburl + "/_api/SP.AppContextSite(#target)/web/lists/getByTitle('" + listTitle + "')/items?#target='" + hostweburl + "'";
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function(data, textStatus, xhr) {
d.resolve(JSON.parse(data.body));
},
error: function(xhr, textStatus, errorThrown) {
d.reject(JSON.parse(xhr.body).error);
}
});
return d.promise;
};
return {
getListItems: getListItems
};
}]);
Solution description
Default.aspx
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
<meta name="WebPartPageExpansion" content="full" />
<!-- Add your CSS styles to the following file -->
<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
<!-- Add your JavaScript to the following file -->
<script type="text/javascript" src="../Scripts/listService.js"></script>
<script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>
and
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div ng-app="SPApp" ng-controller="listController">
</div>
</asp:Content>
App.js
'use strict';
(function() {
var app = angular.module('SPApp', ['SPApp.services']);
app.controller('listController', function ($scope, $q, listService) {
executeOnSPLoaded(function () {
$q.all([listService.getListItems('Documents'), listService.getListItems('Site Pages')]).then(function (data) {
$scope.documentsItems = data[0].d.results;
$scope.sitePagesItems = data[1].d.results;
});
});
});
})();
function executeOnSPLoaded(loaded) {
JSRequest.EnsureSetup();
var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
var scriptbase = hostweburl + "/_layouts/15/";
$.when(
//$.getScript(scriptbase + "SP.Runtime.js"),
$.getScript(scriptbase + "SP.js"),
$.getScript(scriptbase + "SP.RequestExecutor.js"),
$.Deferred(function (deferred) {
$(deferred.resolve);
})
).done(function () {
loaded();
});
}
listService.js
'use strict';
angular.module('SPApp.services',[])
.factory('listService', ['$q', function ($q) {
var getListItems = function (listTitle) {
var d = $q.defer();
JSRequest.EnsureSetup();
var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
var appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]);
var queryUrl = appweburl + "/_api/SP.AppContextSite(#target)/web/lists/getByTitle('" + listTitle + "')/items?#target='" + hostweburl + "'";
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function(data, textStatus, xhr) {
d.resolve(JSON.parse(data.body));
},
error: function(xhr, textStatus, errorThrown) {
d.reject(JSON.parse(xhr.body).error);
}
});
return d.promise;
};
return {
getListItems: getListItems
};
}]);

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>

adding multiple (dynamic number) google charts in page

Am trying to create a test report from the xml file generated from the test suite run. I have to generate the google line chart for each activity in an application node in xml. Its dynamic and we dont know how many activities will be there under application tag.
so far i tried to generate the line charts using the callback method in a for loop but, all the graphs are having the same data. when i debugged the code i found that the code in call back method to create the datatable is always executing for the last activity and generating the same chart for each activity.
here is the code i tried
html
<div id="container">
<div id="report" class="table-responsive">
<select id="app" name="app" aria-placeholder="Select Application">
<option>-- Select Application --</option>
</select>
<select id="activity" name="activity" aria-placeholder="Select Activity">
<option>-- Select Activity --</option>
</select>
<select id="type" name="type" aria-placeholder="Select StartupType">
<option value="coldstart" >Cold</option>
<option value="warmstart" selected>Warm</option>
</select>
<br/>
<div id="chartContainer">
</div>
</div>
<div align="center" class="loader">
<img src="images/loader.gif" id="load" width="400" height="400" align="absmiddle" />
</div>
</div>
javascript
var appXml;
var summaryXml;
$(document).ready(function () {
prepareCharts();
$("#app").change(function () {
var app = $(this).val();
if (app != "") {
$(appXml).find('package').each(function () {
if ($(this).attr('appname') == app) {
var options = '<option value="">-- Select activity --</option>';
$(this).find('activity').each(function () {
options += '<option value="' + $(this).attr('activityname') + '">' + $(this).attr('activityname') + '</option>';
});
$('#activity').html(options);
}
});
}
});
$("#activity").change(function () {
if ($(this).val() != "")
drawActivityChart();
else
drawActivityCharts(appXml, $('#type').val());
});
$('#type').change(function () {
var type = $(this).val();
if ($('#activity').val() == "")
drawActivityCharts(appXml, type);
else
drawActivityChart();
});
});
function prepareCharts() {
$.ajax({
type: "GET",
url: "Startuptime.xml",
dataType: "xml",
success: drawCharts
});
}
function drawCharts(xml) {
console.log('drawing charts');
appXml = xml;
prepareDropdowns(xml);
drawActivityCharts(xml);
}
function prepareDropdowns(xml) {
var options = '<option value="">-- Select application --</option>';
$(xml).find('package').each(function () {
options += '<option value="' + $(this).attr('appname') + '">' + $(this).attr('appname') + '</option>';
});
$('#app').html(options);
$('#app option:nth-child(2)').attr('selected', 'selected').change();
}
function drawActivityCharts(xml, type) {
$('#chartContainer').children().remove();
if (typeof type === 'undefined')
type = 'warmstart';
google.charts.load('current', { 'packages': ['corechart'] });
var app = $('#app').val();
$(xml).find('package').each(function () {
var that = this;
if ($(that).attr('appname') == app) {
var i = 1;
$(that).find('activity').each(function () {
var activityName = $(this).attr('activityname');
console.log(i);
console.log(activityName);
i++;
if ($(this).find(type).length > 0) {
that = this;
$('#chartContainer').append('<div id="' + activityName + '"></div>')
google.charts.setOnLoadCallback(function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Occurance');
data.addColumn('number', 'Time');
var row = 1;
$(that).children(type).find('displaytime').each(function () {
data.addRow([row, parseFloat($.trim($(this).find('timetoinitialdisplay').text()))]);
console.log(row + " " + parseFloat($.trim($(this).find('timetoinitialdisplay').text())));
row++;
});
// Set chart options
var options = {
'title': activityName,
'width': 800,
'height': 200
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById(activityName));
chart.draw(data, options);
});
}
});
}
});
}
function drawActivityChart() {
$('#chartContainer').children().remove();
google.charts.load('current', { 'packages': ['corechart'] });
var app = $('#app').val();
var activity = $('#activity').val();
var type = $('#type').val();
$(appXml).find('package').each(function () {
var that = this;
if ($(that).attr('appname') == app) {
$(that).find('activity').each(function () {
var activityName = $(this).attr('activityname');
if (activityName == activity) {
if ($(this).find(type).length > 0) {
that = this;
$('#chartContainer').append('<div id="' + activityName + '"></div>')
google.charts.setOnLoadCallback(function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Occurance');
data.addColumn('number', 'Time');
var row = 1;
$(that).find('displaytime').each(function () {
data.addRow([row, parseFloat($.trim($(this).find('timetoinitialdisplay').text()))]);
console.log(row + " " + parseFloat($.trim($(this).find('timetoinitialdisplay').text())));
row++;
});
// Set chart options
var options = {
'title': activityName,
'width': 800,
'height': 200
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById(activityName));
chart.draw(data, options);
});
}
}
});
}
});
}
drawActivityCharts() is the method which has to draw the activity charts
and xml schema will be like below.
<?xml version='1.0' encoding='UTF-8' ?>
<appstartuptime>
<package appname="appname" name="packagename" packageversion="version">
<activity activityname="activityname">
<coldstart numberoftimes="1">
<displaytime>
<timetoinitialdisplay>841</timetoinitialdisplay>
</displaytime>
</coldstart>
</activity>
<activity activityname="activityname">
<warmstart numberoftimes="2">
<displaytime>
<timetoinitialdisplay>454</timetoinitialdisplay>
</displaytime>
<displaytime>
<timetoinitialdisplay>467</timetoinitialdisplay>
</displaytime>
</warmstart>
</activity>
</package>
</appstartuptime>
both google.charts.load and google.charts.setOnLoadCallback only need to be called once per page load.
in addition, google.charts.load will wait on the page to load by default,
as such, it can be used in place of $(document).ready
you can also include google's callback in the load statement.
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
or use the promise it returns.
google.charts.load('current', {
packages:['corechart']
}).then(drawChart);
given this, recommend loading google first,
then you can draw as many charts as needed.
i didn't go thru all of the code, but something similar to the following should work...
var appXml;
var summaryXml;
google.charts.load('current', {
packages:['corechart']
}).then(function () {
prepareCharts();
$("#app").change(function () {
var app = $(this).val();
if (app != "") {
$(appXml).find('package').each(function () {
if ($(this).attr('appname') == app) {
var options = '<option value="">-- Select activity --</option>';
$(this).find('activity').each(function () {
options += '<option value="' + $(this).attr('activityname') + '">' + $(this).attr('activityname') + '</option>';
});
$('#activity').html(options);
}
});
}
});
$("#activity").change(function () {
if ($(this).val() != "")
drawActivityChart();
else
drawActivityCharts(appXml, $('#type').val());
});
$('#type').change(function () {
var type = $(this).val();
if ($('#activity').val() == "")
drawActivityCharts(appXml, type);
else
drawActivityChart();
});
});
function prepareCharts() {
$.ajax({
type: "GET",
url: "Startuptime.xml",
dataType: "xml",
success: drawCharts
});
}
function drawCharts(xml) {
console.log('drawing charts');
appXml = xml;
prepareDropdowns(xml);
drawActivityCharts(xml);
}
function prepareDropdowns(xml) {
var options = '<option value="">-- Select application --</option>';
$(xml).find('package').each(function () {
options += '<option value="' + $(this).attr('appname') + '">' + $(this).attr('appname') + '</option>';
});
$('#app').html(options);
$('#app option:nth-child(2)').attr('selected', 'selected').change();
}
function drawActivityCharts(xml, type) {
$('#chartContainer').children().remove();
if (typeof type === 'undefined')
type = 'warmstart';
var app = $('#app').val();
$(xml).find('package').each(function () {
var that = this;
if ($(that).attr('appname') == app) {
var i = 1;
$(that).find('activity').each(function () {
var activityName = $(this).attr('activityname');
console.log(i);
console.log(activityName);
i++;
if ($(this).find(type).length > 0) {
that = this;
$('#chartContainer').append('<div id="' + activityName + '"></div>')
var data = new google.visualization.DataTable();
data.addColumn('number', 'Occurance');
data.addColumn('number', 'Time');
var row = 1;
$(that).children(type).find('displaytime').each(function () {
data.addRow([row, parseFloat($.trim($(this).find('timetoinitialdisplay').text()))]);
console.log(row + " " + parseFloat($.trim($(this).find('timetoinitialdisplay').text())));
row++;
});
// Set chart options
var options = {
'title': activityName,
'width': 800,
'height': 200
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById(activityName));
chart.draw(data, options);
}
});
}
});
}
function drawActivityChart() {
$('#chartContainer').children().remove();
var app = $('#app').val();
var activity = $('#activity').val();
var type = $('#type').val();
$(appXml).find('package').each(function () {
var that = this;
if ($(that).attr('appname') == app) {
$(that).find('activity').each(function () {
var activityName = $(this).attr('activityname');
if (activityName == activity) {
if ($(this).find(type).length > 0) {
that = this;
$('#chartContainer').append('<div id="' + activityName + '"></div>')
var data = new google.visualization.DataTable();
data.addColumn('number', 'Occurance');
data.addColumn('number', 'Time');
var row = 1;
$(that).find('displaytime').each(function () {
data.addRow([row, parseFloat($.trim($(this).find('timetoinitialdisplay').text()))]);
console.log(row + " " + parseFloat($.trim($(this).find('timetoinitialdisplay').text())));
row++;
});
// Set chart options
var options = {
'title': activityName,
'width': 800,
'height': 200
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById(activityName));
chart.draw(data, options);
}
}
});
}
});
}

Facing issue as 404 while Ajax call in typo3

I am new in typo3 and used the ajaxselectlist extension but while the time usage I am facing 404 not found an error.
Below code is fetch from ajaxselectlist/Resources/Templates/OptionRecord/List.html
<script>
jQuery(document).ready(function ($) {
var form = $('#ajaxselectlist-form');
var selectForm = $('.ajaxFormOption');
var controllerpath = $("#uri_hidden").val();
var resultContainer = $('#ajaxCallResult');
var service = {
ajaxCall: function (data) {
console.log("---->"+data.serialize());
$.ajax({
url: controllerpath,
cache: false,
data: {'uid':'1'},
success: function (result) {
resultContainer.html(result).fadeIn('slow');
},
error: function (jqXHR, textStatus, errorThrow) {
resultContainer.html('Ajax request - ' + textStatus + ': ' + errorThrow).fadeIn('fast');
}
});
}
};
form.submit(function (ev) {
ev.preventDefault();
service.ajaxCall($(this));
});
selectForm.change(function () {
resultContainer.fadeOut('slow');
form.submit();
});
selectForm.trigger('change');
});
</script>

How to get items from SharePoint by Current User via REST or JSOM?

I have a SharePoint list with two columns:
users (type people, multiple values allowed)
responsible_department (type string)
I want to get the items from this list where the current user is in the ùsers` field. The field can have multiple users (multiple users allowed)!
I am currently able to get the current user:
var currentUser;
function init() {
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
console.log(currentUser.get_loginName());
}
function onQueryFailed(sender, args) {
console.log('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
No i need to query the mutli user field in my list for all items where my current user is part of the people field. I dont know how to query for this.
Can someone help me out?
I found a solution on MSDN and this works for me:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var siteURL = _spPageContextInfo.webAbsoluteUrl;
var listname = "CustomList";
var currentUserId=_spPageContextInfo.userId;
var url = siteURL + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Title,PeopleField/ID&$filter=substringof('"+currentUserId+"',PeopleField/ID)&$expand=PeopleField/ID";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
var item=items[i];
console.log(item.Title);
}
},
error: function (data) {
}
});
});
</script>

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