2

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

https:‌//xxxx.api.crm6.dynamics.com/api/data/v8.2/<自定义实体>。请求的资源上不存在“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>
4

1 回答 1

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>
于 2017-04-07T08:11:59.223 回答