Angular 4 前端中的 CORS 问题,Google Cloud Endpoints 运行 go API 后端

Posted

技术标签:

【中文标题】Angular 4 前端中的 CORS 问题,Google Cloud Endpoints 运行 go API 后端【英文标题】:CORS issue in Angular 4 frontend with Google Cloud Endpoints running a go API backend 【发布时间】:2018-03-11 08:02:04 【问题描述】:

我无法从 Angular 4 前端调用在云端点后面的谷歌云中运行的 API。我收到以下错误:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:4200' 不允许访问。响应的 HTTP 状态代码为 403。

我也在本地机器上运行 swagger 并从 swagger 成功调用 API。 我的各种设置如下: OpenAPI(Swagger 规范):

host: MyApp.appspot.com
x-google-endpoints:
  - name: MyApp.appspot.com
    allowCors: true

GO 服务器 CORS 设置:   我正在使用“github.com/rs/cors”库

c := cors.New(cors.Options
        AllowedOrigins:   []string"*",
        AllowedHeaders:   []string"*",
        AllowedMethods:   []string"GET", "PUT", "POST", "HEAD", "POST",
        AllowCredentials: true,
    )

Angular 4 应用程序:

const payloadHeaders = new Headers('Access-Control-Allow-Origin' : 'http://localhost:4200','authorization':'Bearer *********');
    var url = 'https://MyApp.appspot.com/users/user?u=' + username;
    this.http.get(url,headers:payloadHeaders).timeout(3000)
    .map((response) => 
      return response.json();
    ).subscribe(

swagger 和 angular 之间的唯一区别可能是它们如何发出 http 请求……尽管我不确定。 Swagger 起源是 '127.0.0.1:64298' 而 Angular 是 'localhost:4200'

有谁知道我可以如何克服这个 CORS 问题?

Stackdriver 日志抛出:Endpoints management skipped for an unrecognized >HTTP call: OPTIONS /users/user?u=xxxx@yyyy.com 但我认为我已经在 GO 服务器本身中处理了这一点。所以这有点>令人困惑。

谢谢!

【问题讨论】:

No 'Access-Control-Allow-Origin' header in Angular 2 app的可能重复 侯赛因,答案中提供的解决方案根本行不通。 Hussain 不是我的名字,你有没有得到使用 curl bash 的 http 调用?你确定请求正在通过吗?您是否可以提供或澄清任何其他信息 嗯,Hussin,http 调用使用 curl bash 工作,我很确定请求正在通过。 如果您仔细阅读该问题,您将掌握所有细节以了解正在发生的事情。只是一个温和的提醒,它不仅仅是关于角度,请仔细阅读问题细节。 【参考方案1】:

最后我犯了一个愚蠢的错误。我错过了 Angular 中的路径组件。现在可以正常使用了。

【讨论】:

以上是关于Angular 4 前端中的 CORS 问题,Google Cloud Endpoints 运行 go API 后端的主要内容,如果未能解决你的问题,请参考以下文章

Go Restful API:CORS 配置适用于 React 但不适用于 Angular

Angular 4 App调用Play Framework Web App的CORS问题

CORS 不适用于 .NET Core API 和 Angular 前端

Keycloak Spring boot 后端和 Angular 前端,CORS 错误

CORS Angular 10 ASP.Net

从 Angular 前端到 json-server 的 GET 调用访问被 CORS 策略阻止的 XMLHttpRequest