【问题标题】:Why do I get a CORS error only with Angular? [duplicate]为什么只有 Angular 才会出现 CORS 错误? [复制]
【发布时间】:2022-01-18 13:14:54
【问题描述】:

当我使用 Angular 向我的 API 网关发送请求时,出现此错误:
*CORS 策略已阻止从源“http://localhost:4200”访问“https://example.com”处的 XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头。 *

如果我添加 'Access-Control-Allow-Origin':'*' 我有这个:
*从源“http://localhost:4200”访问“https://example.com”上的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制-请求的资源上存在 Allow-Origin' 标头。*

但同样的请求可以完美地与 CURL、Web 浏览器和另一个移动应用程序 (Flutter) 配合使用。
我尝试在 API Gateway 中启用(使用 Access-Control-Allow-Origin:'*')并禁用 CORS,但问题仍然存在。
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class mainService {
  constructor(private http: HttpClient) {}

  getAll() {
    return this.http.get<any>("https://example.com", 
      {
        headers: HttpHeaders({'Access-Control-Allow-Origin':'*'})
    });
  }
}

【问题讨论】:

    标签: angular cors aws-api-gateway


    【解决方案1】:

    MDN's description of CORS中所述

    出于安全原因,浏览器会限制从脚本发起的跨域 HTTP 请求。例如,XMLHttpRequest 和 Fetch API 遵循同源策略。这意味着使用这些 API 的 Web 应用程序只能从加载应用程序的同一来源请求资源,除非来自其他来源的响应包含正确的 CORS 标头。

    您的 curl、Web 浏览器和 Flutter 应用程序没有通过脚本调用您的后端 API。只有您的 Angular 应用程序使用 XMLHttpRequest 来获取数据。 要解决此问题,您需要允许来自后端应用程序的 Cors

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2021-05-21
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多