【问题标题】:ajax get request to Office365 REST Api fails CORS?ajax 获取对 Office365 REST Api 的请求失败 CORS?
【发布时间】:2015-04-03 06:57:20
【问题描述】:

我正在尝试从本地服务器向 Office365 RESTful API 服务发出 ajax GET 请求,但遇到了跨域 HTTPRequest 错误。以下是我的“get-files-at-root”尝试的示例:

$.ajax({
  url: 'https://[sharepoint_site]/_api/v1.0/me/files?access_token='+token,
  type: 'get',
  dataType: 'json',
  success: function(data) {
    if (success){
      success(data);
    }
  },
  error: error
})

我从服务器收到以下响应:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403.

我已尝试将访问令牌作为标头参数发送:

headers: {'Authorization': 'Bearer '+ token}

但结果相同。

关于我做错了什么有什么想法吗?

(背景:我正在尝试在客户端上创建自己的 Office365“文件选择器”,因为我找不到提供此功能的 OneDrive Business 可用库。)

【问题讨论】:

  • 您确定 Sharepoint REST API 支持 CORS?
  • 他们现在这样做了!见下文...

标签: ajax cors office365


【解决方案1】:

Office 365 文件 API 和 SharePoint REST 刚刚引入了对 CORS 的支持。

https://msdn.microsoft.com/en-us/office/office365/howto/create-web-apps-using-CORS-to-access-files-in-Office-365

您尝试做的正是它的工作原理。该服务将使用 Access-Control-Allow-Origin 标头响应 OPTIONS 飞行前请求。

请求中的授权必须是 Azure Active Directory 颁发的 OAuth2 隐式授予访问令牌。

【讨论】:

  • 像魅力一样工作!谢谢!
【解决方案2】:

您对 CORS 一无所知。阅读规范:http://www.w3.org/TR/cors/

在您的情况下,您必须允许 null 来源,因为我们正在谈论 localhost。您必须允许您发送的方法和标头,甚至是 content-type 标头。您必须允许发送凭据,您可以在 Authorization 标头中获取。您必须使用200 ok 处理OPTIONS 请求。

【讨论】:

    【解决方案3】:
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    

    【讨论】:

      【解决方案4】:

      您可以尝试在标题中设置 Access-Control-Allow-Origin,如下所示。

      headers: { 'Access-Control-Allow-Origin': '*' }
      

      【讨论】:

      • 这个标头必须作为响应的一部分发送,而不是请求。
      猜你喜欢
      • 1970-01-01
      • 2013-12-06
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2018-03-06
      • 2021-05-22
      相关资源
      最近更新 更多