1

I am trying to access lists within SP hosted add in from outside its context.

Using the Content Editor WebPart I have placed some javascript (to make the request) on a sub site of my site collection e.g.https://work.sharepoint.com/teams/d/sandbox/

My SP app addin is hosted in the same site collection e.g. https://work-9850ba148f9a52.sharepoint.com/teams/d/MyApp/

I am using the following code to try and get the lists data from the add in but it gives me a 403 error.

Maybe I have mixed up the hostweburl and the appweburl?

Advice appreciated!

function GetLists() {

var executor;
var hostweburl= "https://work-9850ba148f9a52.sharepoint.com/teams/d/MyApp/"
var appweburl = "https://work.sharepoint.com/teams/d/sandbox/"

executor = new SP.RequestExecutor(hostweburl);
executor.executeAsync(
{url: appweburl + "_api/SP.AppContextSite(@target)/web/lists/?@target='" + hostweburl + "'",
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data) {

            console.log(data);

        },
        error: function (error) {
            console.log(JSON.stringify(error));
        }
            }
        );
    }
1

You need to update your executor:

    var executor = new SP.RequestExecutor(appweburl);

It should be appweburl instead of hostweburl.

  • I have updated the executor to appweburl but I get the same error. – Damien Flood Jan 25 '18 at 10:16
1

Ensure that you have give adequate permissions in the Appmanifest.xml file.

It should be site collection read atleast to get data from the site collection.

SP-hosted app works on user+app permission. So, ensure that the user has adequate permission to read data from the list.

enter image description here

If its not give, please provide permission and then upload the app again.

  • The SiteCollection permission is set to FullControl in the Appmanifest.xml. Any ideas? – Damien Flood Jan 25 '18 at 12:44
  • how about changing values of host web and app web to var hostweburl = "https://work.sharepoint.com/teams/d/sandbox/" var appweburl= "https://work-9850ba148f9a52.sharepoint.com/teams/d/MyApp/" ? – Gautam Sheth Jan 25 '18 at 14:08
0

Please access appweb and hostweb url like below instead of hard code:

 <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>

    <script type="text/javascript">
        // Set the style of the client web part page to be consistent with the host web.
        (function () {
            'use strict';
            var hostUrl = '';
            if (document.URL.indexOf('?') != -1) {
                var params = document.URL.split('?')[1].split('&');
                for (var i = 0; i < params.length; i++) {
                    var p = decodeURIComponent(params[i]);
                    if (/^SPHostUrl=/i.test(p)) {
                        hostUrl = p.split('=')[1];
                        document.write('<link rel="stylesheet" href="' + hostUrl + '/_layouts/15/defaultcss.ashx" />');
                        break;
                    }
                }
            }
            if (hostUrl == '') {
                document.write('<link rel="stylesheet" href="/_layouts/15/1033/styles/themable/corev15.css" />');
            }
        })();
    </script>

    <%-- Internal blog --%>
    <script type="text/javascript">
        var hostweburl;
        var appweburl;
        // Load the required SharePoint libraries
        $(document).ready(function () {
            //Get the URI decoded URLs.
            hostweburl =
                decodeURIComponent(
                    getQueryStringParameter("SPHostUrl")
            );
            appweburl =
                decodeURIComponent(
                    getQueryStringParameter("SPAppWebUrl")
            );
            // resources are in URLs in the form:
            // web_url/_layouts/15/resource
            var scriptbase = hostweburl + "/_layouts/15/";
            // Load the js files and continue to the successHandler
            $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
        });
        // Function to prepare and issue the request to get
        //  SharePoint data
        function execCrossDomainRequest() {
            // executor: The RequestExecutor object
            // Initialize the RequestExecutor with the app web URL.
            var executor = new SP.RequestExecutor(appweburl);
            // Issue the call against the app web.
            // To get the title using REST we can hit the endpoint:
            //      appweburl/_api/web/lists/getbytitle('listname')/items
            // The response formats the data in the JSON format.
            // The functions successHandler and errorHandler attend the
            //      sucess and error events respectively.
            executor.executeAsync(
                {
                    url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Posts')/items?@target='" + hostweburl + "/blog'&$top=1",
                    method: "GET",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: successHandler,
                    error: errorHandler
                }
            );
        }
        // Function to handle the success event.
        // Prints the data to the page.
        function successHandler(data) {
            var jsonObject = JSON.parse(data.body);
            var blogsHTML = "";
            var results = jsonObject.d.results;
            for (var i = 0; i < results.length; i++) {
                blogsHTML = blogsHTML + "<div><a href=\"" + hostweburl + "/blog/Lists/Posts/Post.aspx?ID=" + results[i].ID + "\" target=\"_blank\">" + results[i].Title + "</a></div><br>";
            }
            $('#internal').append(blogsHTML);
        }
        // Function to handle the error event.
        // Prints the error message to the page.
        function errorHandler(data, errorCode, errorMessage) {
            document.getElementById("internal").innerText =
                "Could not complete cross-domain call: " + errorMessage;
        }
        // Function to retrieve a query string value.
        // For production purposes you may want to use
        //  a library to handle the query string.
        function getQueryStringParameter(paramToRetrieve) {
            var params =
                document.URL.split("?")[1].split("&");
            var strParams = "";
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split("=");
                if (singleParam[0] == paramToRetrieve)
                    return singleParam[1];
            }
        }
    </script>

And here is the complete demo about accessing host web list in SharePoint add-in:

Build a SharePoint Hosted App to access list data in your Host Web using the REST API in 10 Easy Steps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.