I am trying to perform POST operations in SharePoint 2013 environment using REST API from external application running under the same company domain. Till now I am to do the GET operation successfully but while performing the POST Action from the same steps I am getting Error 401 (Unauthorized) even though I am the Site Collection Administrator of the site. Below is the code that I am trying.
var hostUrl = "http://mycompany.sharepoint.com/sites/site1/SharePoint/oAuth";
function getFormDigest() {
console.log("Getting Form Digest..");
$.support.cors = true;
var _formDigest;
$.ajax({
url: hostUrl + "/_api/contextinfo",
type: "POST",
dataType: "json",
headers: { "Accept": "application/json; odata=verbose" },
xhrFields: { withCredentials: true },
async: false,
success: function (data) {
_formDigest = data.d.GetContextWebInformation.FormDigestValue;
console.log(data.d.GetContextWebInformation.FormDigestValue);
console.log("Form Digest Done");
},
error: function () {
console.log("Error Occured");
}
});
return _formDigest;
}
function AddListItem() {
var _digest = getFormDigest();
console.log("Add List item called with digest value -- " + _digest);
$.ajax
({
url: "http://mycompany.sharepoint.com/sites/site1" + "/_api/web/lists/GetByTitle('TestList')/items",
type: "POST",
data: JSON.stringify
({
__metadata:
{
type: "SP.Data.TestListListItem"
},
Title: "SharePoint"
}),
xhrFields: { withCredentials: true },
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": _digest
},
success: function (data, status, xhr) {
console.log("Item Inserted..!!");
},
error: function (xhr, status, error) {
console.log("Error Occured");
}
});
}
I am able to get the Form Digest value properly and the above code is working fine when I am using the code inside SharePoint Page using content editor web part. And I have already done the CORS part after which I am able to do the GET request.
Thanks in advance..