Web资源上的Dynamics CRM Web API身份验证错误

时间:2016-11-24 07:51:52

标签: dynamics-crm-online dynamics-crm-webapi

使用HTML网络资源加载Dynamics CRM表单时,我从Chrome浏览器控制台收到以下错误消息。

  

https:// xxxx.api.crm6.dynamics.com / api / data / v8.2 /< custom entity>。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' https://.crm6.dynamics.com'因此不允许访问。响应的HTTP状态代码为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>

1 个答案:

答案 0 :(得分:1)

您似乎正在向另一个域请求。你确定你的clientUrl在同一个域上吗?

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!");
}

很多人都遇到了$ .ajax和XmlHttpRequest的问题。幸运的是有图书馆,会照顾这个。 crm-sdk的示例,它将与您的代码相同:

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