I'm trying to use RESTful services to return all replies in a SharePoint sitefeed. Currently, I am successfully using this code to retrieve the sitefeed's posts:
function getFeed(){
var feed;
var reply;
var rCounter;
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/actor(item=#v)/feed?#v=%27https://<mysite>.sharepoint.com/<sitename>/newsfeed.aspx%27",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
myFeed = $(data);
console.log(myFeed);
for (i = 0; i < myFeed[0].d.SocialFeed.Threads.results.length; i++) {
feed = (myFeed[0].d.SocialFeed.Threads.results[i].RootPost.Text);
console.log(myFeed[0].d.SocialFeed.Threads.results[0].Actors.results[1].Name + ": " + feed);
if (myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length >0){
rCounter = myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length;
for (j = 0; j < myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length; j++) {
rCounter--;
reply = myFeed[0].d.SocialFeed.Threads.results[i].Replies.results[rCounter].Text;
console.log(reply);
}
}
console.log("* * * * * * * * *");
}
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
However, this gives me the posts but with only the two latest replies. According to this MSDN post, I need to use a POST method to get all replies and pass in the thread ID. So I made a new function:
function getPost(){
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/post(ID=ai)/?#ai='8.211b75cd6dc84fe4bc6c3e9f46971f51.97717348cd3048768103d55751dc0e2d.211b75cd6dc84fe4bc6c3e9f46971f51.819bde2276b948a8a120964289476489.17c08f26b90a4b659ff1fcfb0ede4025.5.5.1'",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
console.log($(data));
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
When I run this new function, I get a 403 (FORBIDDEN) error. Can someone tell me what I'm doing wrong?
try passing headers like below.
function getPost(){
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/post(ID=ai)/?#ai='8.211b75cd6dc84fe4bc6c3e9f46971f51.97717348cd3048768103d55751dc0e2d.211b75cd6dc84fe4bc6c3e9f46971f51.819bde2276b948a8a120964289476489.17c08f26b90a4b659ff1fcfb0ede4025.5.5.1'",
method: "POST",
headers: { "Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() },
success: function (data) {
// Returning the results
console.log($(data));
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
Related
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>
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.
How to read sharepoint list items from a specific folders using Javascript/Jquery through JSOM or REST?
Using JSOM or CSOM, you need to specify 'FileDirRef' property in CAML Query, and add 'RecursiveAll' scope:
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View Scope="RecursiveAll"> " +
"<Query>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name="FileDirRef" />" +
"<Value Type=\"Text\">yourFolderPath</Value>" +
"</Eq>" +
"</Where>" +
"</Query>" +
"</View>');
function GetFolders() {
var oWeb = _spPageContextInfo.webAbsoluteUrl;
var URLC = oWeb + "/_api/web/lists/getByTitle('ListName')/items";
$.ajax({
url: URLC,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
cache: false,
success: function (data) {
$.each(data.d.results, function (index, item) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('ListName/ListFolder)/listitemallfields/",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
cache: false,
success: function (data) {
}
});
})
},
error: function (data) { }
});
}
You can use REST API to read list items from a specific folders using getfolderbyserverrelativeurl.
Refer below Code :
var folderRelativeUrl = "Relative_URL_Of_Your_Folder"; //here specify relative URL of your folder (e.g. '/Shared Documents')
getItemFromFolder().then(getItemFromFolderSuccess, getItemFromFolderFailed);
function getItemFromFolder(){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('" + folderRelativeUrl + "')/files?$expand=ListItemAllFields",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getItemFromFolderSuccess(data){
// success handler
var response = data.d.results; // This is Response Object from Server
}
function getItemFromFolderFailed(error){
// error handler code
}
I am trying to construct the correct URL to return the items in a SharePoint View using the REST api.
Using my browser and the following URL I can return the items in the list.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Items
And I can get the view definition using the following URL.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Views/getbytitle('Latest News')/
But I cannot figure out what I need to put at the end of that URL to actually get the items that are returned by the the View.
SP.View object does not contain any methods for manipulating list items. But SP.View object contains SP.View.viewQuery property that specifies the query that is used by the list view. That means the following approach could be used for retrieving list items for view:
perform the first request to get CAML Query for List View using SP.View.viewQuery property
perform the second request to retrieve List Items by specifying CAML Query
How to return list items for a List View using REST API using JavaScript
function getJson(url)
{
return $.ajax({
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return $.ajax({
url: url,
method: "POST",
data: JSON.stringify(queryPayload),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose"
}
});
}
function getListItemsForView(webUrl,listTitle,viewTitle)
{
var viewQueryUrl = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return getJson(viewQueryUrl).then(
function(data){
var viewQuery = data.d.ViewQuery;
return getListItems(webUrl,listTitle,viewQuery);
});
}
Usage
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'Announcements','Latest News')
.done(function(data)
{
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
console.log(items[i].Title);
}
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
I'm trying to post a wall message from a local desktop application (I can't use the FB JS SDK).
Here's a a snippet of my code
var url = "https://graph.facebook.com/me/feed";
var params = "access_token=" + token + "&message=" + encodeURI(text);
$.ajax({
crossDomain: true,
data: params,
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
The request ignores the message parameter.
I receive a list of feeds as it were a GET request.
I've tried to set the parameters as map but it didn't help.
BTW - when using CURL (in C++) i manage to post the data correctly.
Any ideas why it ignores the parameters?
I would put the "params" into the data element like so:
var url = "https://graph.facebook.com/me/feed";
$.ajax({
crossDomain: true,
data: { access_token: token, message: text },
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
Let jQuery encode the parameters from there.
Below worked fine in Jquery 1.6.4 + jquery.mobile-1.0rc2 by setting $.mobile.allowCrossDomainPages = true; in mobileinit bind
$.ajax( {
url : "https://graph.facebook.com/me/feed",
type : "POST",
data : "access_token=" + your_access_token + "&message=my first wall post",
cache : false,
success : function(res) {
if (!response || response.error) {
alert("Couldn't Publish Data");
} else {
alert("Message successfully posted to your wall");
}
},
error : function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
}
});