首页 > 解决方案 > 请求的资源上不存在“Access-Control-Allow-Origin”标头(角度)

问题描述

我正在制作一个角度应用程序,该应用程序向 AWS API 网关发出发布请求,然后调用 Lambda 函数,请注意我调整了 AWS API GATEWAY 中的 CORS 设置,除了“Acessc-Control-Allow”之外,没有任何预期的标题-起源'

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

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.

标签: angularlambdacorsxmlhttprequestserverless

解决方案


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

这有帮助: URL: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。

希望这可以帮助。


推荐阅读