【问题标题】:How can I resolve CORS problems when accessing the SharePoint-API via AJAX-request?通过 AJAX 请求访问 SharePoint-API 时如何解决 CORS 问题?
【发布时间】:2019-12-03 17:43:41
【问题描述】:

我为客户设置了 Dynamics-Portal。客户希望在门户上显示来自 SharePoint 的图像。

我的想法是使用带有 Ajax 的 jQuery 来访问 SharePoint-API。

由于我的网络编程经验相当有限,我需要帮助来了解我遇到的错误。

经过阅读,这是我的第一次尝试:

$.ajax({
          url: "https://example.SharePoint.com/_api/web/GetFolderByServerRelativeUrl('/ImageFolder')/Files",
          type: 'GET',
          Accept: "application/json;odata=verbose",
          crossDomain: true,
          contentType: 'application/json;odata=verbose',
          dataType: 'json',
          xhrFields: { withCredentials: true }
        })

这会产生以下错误:

Access to XMLHttpRequest at 'https://example.SharePoint.com/_api/web/GetFolderByServerRelativeUrl('/ImageFolder')/Files'
    from origin 'https://myDynamicsPortal.com' has been blocked by CORS policy:
    Response to preflight request doesn't pass access control check:
    The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

现在我通过添加“?callback=?”来更改上面的 Ajax到网址。像这样:

url:"https://example.SharePoint.com/_api/web/.../Files?callback=?"

这似乎和改变一样:

dataType: 'json'
to
dataType: 'jsonp'

错误消失了,但出现了这个警告:

Cross-Origin Read Blocking (CORB) blocked cross-origin response
https://example.SharePoint.com/_api/web/GetFolderByServerRelativeUrl('/ImageFolder')/Files?callback=jQuery13423412342134134_1234123412341234&_=12341341234 
with MIME type application/atom+xml.

See https://www.chromestatus.com/feature/5629709824032768 for more details.

状态码为 200,但出现错误:"JQuery13423412342134134_1234123412341234 was not called"

我从这些错误、警告和我的研究中理解/解释的是:

一旦需要凭据,服务器就不能再将通配符用于允许的来源。由于我无法更改 SharePoints 源策略,因此我寻找其他方法来解决该问题。

似乎服务器不明白我期望回调,因为我没有配置“jsonp”或“?callback=?”。这样做后,错误消失了,但似乎由于 CORB(跨源读取阻塞),我的门户将不接受响应。

为什么 SharePoint 突然接受我的请求? (或者是吗?)

为什么我会获得 http 200 成功 - 但是这个错误:

"JQuery13423412342134134_1234123412341234 was not called"

同时出现解析错误?

提前致谢并致以最诚挚的问候

杰克

【问题讨论】:

    标签: jquery ajax sharepoint cors dynamics-365


    【解决方案1】:

    尝试添加代码(support.cors):

    $.support.cors = true;
    

    【讨论】:

    • 感谢您的建议。同时我发现,在我的场景中这是不可能的,因为我无法更改 SharePoint 的 CORS 设置。
    【解决方案2】:

    显然,在这种情况下这是不可能的,因为我无法更改 SharePoint 的 CORS 设置。解决方案似乎是 SharePoint 加载项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-03
      • 2022-06-12
      • 1970-01-01
      • 2019-08-19
      • 2017-07-18
      • 2018-06-11
      • 2015-05-11
      相关资源
      最近更新 更多