angular - 请求的资源上不存在“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.
解决方案
几个小时前我通过了同样的问题。
这有帮助: 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。
希望这可以帮助。
推荐阅读
- python-3.x - 在哪里使用 core-python 地图功能?
- react-native - 为什么我的 appbundle 有这个问题?
- python - 变量不会更改为“int” - 停留在“str”
- python - cx_Freeze : 导入模块失败
- php - PHP - 通过变量动态调用对象方法
- javascript - 为什么数组字面量和 BufferArray 之间的性能差距如此之大?
- haskell - 通过条件停止迭代循环并返回与条件匹配的值
- google-apps-script - 在对象 Gmail 线程中找不到函数 removeLabel
- r - 如何对LM摘要中的系数进行排序?
- python - 将现有的 NumPy 数组转换为 ctype 数组以在多处理之间共享