【问题标题】:How to make Graph API calls from Angular http://localhost:4200 port?如何从 Angular http://localhost:4200 端口进行 Graph API 调用?
【发布时间】:2021-11-17 15:48:14
【问题描述】:

我在 Angular 中创建了一个项目。我需要从 SharePoint 列表中获取/发布数据。

我已经创建了 Microsoft Graph API 应用来实现同样的目的。

当我尝试使用 Postman 在 SharePoint 列表中获取/发布数据时。它工作正常。

但是当我在 Angular 中集成该代码并在 localhost 上运行该项目时,会出现以下错误。

“从源 'http://localhost:4200' 访问 'https://login.microsoftonline.com/{ {directoryId}}/oauth2/v2.0/token' 的 XMLHttpRequest 已被 CORS 策略阻止: 请求的资源上不存在“Access-Control-Allow-Origin”标头。”

【问题讨论】:

    标签: angular azure-active-directory microsoft-graph-api localhost sharepoint-online


    【解决方案1】:

    当我们开发一个需要后端来持久化数据的 Angular 应用程序时,后端通常在 localhost 的另一个端口上提供服务。例如,前端 Angular 应用程序的 URL 是 http://localhost:4200,而后端服务器的 URL 是 http://localhost:3000。在这种情况下,如果我们从前端应用程序向后端服务器发出 HTTP 请求,这是一个跨域请求,我们需要做一些额外的工作才能实现。

    • 在我们项目的 package.json 旁边创建一个名为 proxy.conf.json 的文件

    • 将以下内容添加到新创建的proxy.conf.json 文件中:

      {
      "/api": {
        "target": "http://localhost:3000",
        "secure": false
      }
      

      }

    • 编辑package.json文件的启动脚本为:

    "start": "ng serve --proxy-config proxy.conf.json",

    了解更多https://betterprogramming.pub/setup-a-proxy-for-api-calls-for-your-angular-cli-app-6566c02a8c4d

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2016-11-28
      • 2019-11-16
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多