请求的资源(英语)上没有“ Access-Control-Allow-Origin”标头

时间:2019-07-12 01:53:11

标签: angular lambda cors xmlhttprequest serverless

我正在提出一个有角度的应用程序,该应用程序向     AWS API网关会调用Lambda函数,请注意,     调整了AWS API网关中的CORS设置,没有任何内容     除“ Acessc-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.

1 个答案:

答案 0 :(得分:0)

几个小时前我通过了同一期杂志。

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

这是我的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。

希望这会有所帮助。