2

When loading a Dynamics CRM form with a HTML web resource I get the below error from the Chrome browser console.

https:‌//xxxx.api.crm6.dynamics.com/api/data/v8.2/<custom entity>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://.crm6.dynamics.com' is therefore not allowed access. The response had HTTP status code 401.

<script type="text/javascript">

 var clientUrl = "https://xxxx.api.crm6.dynamics.com/api/data/v8.2/"

 function GetAccounts() {
    var url = clientUrl + "accounts"

    $.ajax({
        method: "GET",
        url: url,
        async: false,
        beforeSend: getAccountsBeforeSendCallback,
        fail: getAccountsFailCallback,
        done: getSavingGoalsDoneCallback,
        success: getAccountsSuccessCallback
    });
}

 function getAccountsBeforeSendCallback(jqXHR, settings) {
    debugger
    jqXHR.setRequestHeader("OData-MaxVersion", "4.0");
    jqXHR.setRequestHeader("OData-Version", "4.0");
    jqXHR.setRequestHeader("Accept", "application/json");
    jqXHR.setRequestHeader("Content-Type", "application/json; charset=utf-8");
}
</script>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3845056
  • 489
  • 7
  • 25
  • Most discussed topic in general. CORS & JSONP will do the trick. https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource – Arun Vinoth-Precog Tech - MVP Jul 03 '17 at 18:43

1 Answers1

1

It seems you're doing a request to another domain. Are you sure your clientUrl is on same domain?

var clientUrl = "https://xxxx.api.crm6.dynamics.com/api/data/v8.2/";
var rightUrl = window.Xrm.Page.context.getClientUrl() + "/api/data/v8.2";
if (clientUrl !== rightUrl) {
    console.log("You will get the 'Access-Control-Allow-Origin' error!");
}

A lot of people have trouble with the $.ajax and XmlHttpRequest stuff. Luckily there are libraries, which will take care for this. Example of crm-sdk, which will do same as your code:

<script type="text/javascript" src="CRMSDK.js"></script>
<script type="text/javascript">
    var WebAPI = window.CRMSDK.WebAPI;
    WebAPI.retrieveMultiple("account").then(function (data) {
        getAccountsSuccessCallback(data); //this is your method.
    });
</script>
Niels Steenbeek
  • 4,692
  • 2
  • 41
  • 50