Introduction
While developing a Sharepoint hosted app in Office365/Sharepoint online environment for the first time, I have faced some challenges in Rest API call, I have used the same Rest query as I used previously in my Sharepoint hosted apps which I developed and deployed in onprem, but here in Office365, some unauthentication errors like 403/401 were thrown.
In this post, I have mentioned some workarounds for the issues that I faced.
Solution
- Always refer to the js source files and Ajax reference in the below order:
<script type="text/javascript" src="../Scripts/jquery-1.7.1.min.js"></script>(Any JS Reference)
<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>
- Use cross-domain library JS file (sp.requestexecutor.js) for Rest API calls:
$.getScript(scriptbase + "SP.RequestExecutor.js",getHostListData);
function getHostListData() {
var reqestUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle
('listName')/items?@target='" + hostweburl + "'";
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync(
{
url: reqestUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
}
);
}
function successHandler(data) {
}
function errorHandler(data, errorCode, errorMessage) {
}