【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource (ANGULAR)请求的资源上不存在“Access-Control-Allow-Origin”标头(角度)
【发布时间】:2019-11-21 18:25:00
【问题描述】:

我正在制作一个 Angular 应用程序,该应用程序向 然后调用 Lambda 函数的 AWS API 网关,请注意我 调整了 AWS API GATEWAY 中的 CORS 设置,没有任何东西 预期作为标题,除了“Accesssc-Control-Allow-Origin”

下面是我的代码和我的错误

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';



const body = {
  "body": "query{product(name:\"CIB\"){high}}"
}


@Component({
  selector: 'app-grid-tiles',
  templateUrl: './grid-tiles.page.html',
  styleUrls: ['./grid-tiles.page.scss'],
})
export class GridTilesPage implements OnInit {



  constructor(private http: HttpClient) { }
   httpdata;
   ngOnInit() {
      this.http.post("https://3ra64ngnc2.execute-api.us-east-1.amazonaws.com/dev/test",body,{ 
        headers: new HttpHeaders({
          "Access-Control-Allow-Origin": "POST" ,

        })      
      })
      .subscribe((data) => this.displaydata(data));     
   }
   displaydata(data) {this.httpdata = data;}
}

这是控制台产生的错误

Access to XMLHttpRequest at 'https://3ra64ngnc2.execute-api.us-east-1.amazonaws.com/dev/test' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

【问题讨论】:

  • 您是否尝试将其更改为 - "Access-Control-Allow-Origin": "*"?另一方面,CORS 通常会被浏览器阻止,因此可以安装 chrome 中的扩展,因此浏览器不再阻止 CORS 请求。
  • 是的,我尝试使用“*”而不是“POST”,但我遇到了同样的错误,但是你能告诉我什么扩展可以解锁它吗?
  • 只需在浏览器中搜索 - 允许 CORS: Access-Control-Allow-Origin 并添加扩展至 chrome

标签: angular lambda cors xmlhttprequest serverless


【解决方案1】:

几个小时前我通过了同样的问题。

这有助于: 网址:https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#how-to-cors-console 使用 API Gateway 控制台在资源上启用 CORS,第 4 点。

这是我的 Angular 代码。 (注意我用的是http.get)

 const httpOptions = {
     headers: new HttpHeaders({
         'Content-Type': 'application/json',
         'x-api-key': 'my api key'
     })
};


private batteriesURL: string = 'https....my URL';

getAllBatteries(): Observable<any[]> {
     return this.http.get<any[]>(this.batteriesURL, httpOptions).pipe(
         tap(data => JSON.stringify(data)),
         catchError(this.handleError)
);}

我们要做的最后一件事是更新 PHP 上的 php 代码以允许 CORS,然后是 CORB。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-11-29
    • 2014-07-28
    • 2014-01-19
    • 2013-12-07
    相关资源
    最近更新 更多