jquery - 通过 AJAX 请求访问 SharePoint-API 时如何解决 CORS 问题?
问题描述
我为客户设置了 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"
连同解析错误?
提前致谢并致以最诚挚的问候
杰克
解决方案
尝试添加代码(support.cors):
$.support.cors = true;
推荐阅读
- python - 列表推导中的嵌套循环和条件检查(python)
- python - 为什么我需要在我的 while 循环中定义变量才能让我的代码工作?
- mysql - MySQL 的解决方案还不支持 'LIMIT & IN/ALL/ANY/SOME 子查询'
- python - 如何在 boto3 python 中使用过滤器返回多个子网(值)?
- symfony - 如何使用基于连接字段的 Doctrine 过滤器?
- java - Java几何问题:圆弧的周长
- sql - 按年份返回最大值和相应 FK(ID) 组的查询,该查询来自另一个按 FK(ID) 和年份平均分组的选择
- django - 为什么 Django 扩展用户模型在更新字段时无法显示预填充的数据?
- python - ValueError: len(index) != len(labels) for groupby pandas
- perl - 在 Perl 中将字符串编码为 UTF-8