Question

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..

Was it helpful?

Solution

Finally got it working. Since we are trying to send the credentials over the request, firstly the preflight OPTIONS request is sent to SharePoint server without credentials which returns the 401 error, so our main request is dropped automatically. I referred this LINK which contains the detailed explanation of error and the solution.

Happy coding..

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top