如何解决通过 AJAX-请求访问 SharePoint-API 时的 CORS 问题?

How can I resolve CORS problems when accessing the SharePoint-API via AJAX-request?

我已经为客户设置了一个 Dynamics-Portal。客户想要在门户上显示来自 SharePoint 的图像。

我的想法是使用 jQuery 和 Ajax 访问 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。像这样:

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"

我 understood/interpreted 从这些错误、警告和我的研究中得到的是:

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

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

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

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

"JQuery13423412342134134_1234123412341234 was not called"

连同解析错误?

在此先致谢并致以最诚挚的问候

杰克

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

$.support.cors = true;

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