【发布时间】:2023-04-07 14:28:01
【问题描述】:
无法弄清楚为什么回复是null。
当使用模拟数据进行测试时,它工作得非常好,但是当我尝试访问托管在 AWS EC2 中的 API 时,响应为 null,并且控制台中的错误消息如下所示
Cross-Origin Read Blocking (CORB) blocked cross-origin response http://example.com/search/api?limit=10&offset=10 with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
但是,我在浏览器的网络选项卡中验证,它显示200 OK。此外,我使用 Postman 客户端验证了此 API 调用,并且正在显示数据。
我尝试了各种方法来禁用 Chrome 浏览器中的网络安全选项,但都没有成功。我的 Chrome 浏览器中也有 CORS 扩展。
谁能指导我在这里做错了什么。
服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class SearchService {
searchUrl = 'http://example.com/search/api?limit=10&offset=10'
mockDataUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private httpClient: HttpClient) { }
getMockData() {
return this.httpClient.get(this.mockDataUrl);
}
getSearchData() {
return this.httpClient.get(this.searchUrl);
}
}
组件
export class AppComponent implements OnInit {
ngOnInit() {
this.searchService.getSearchData().subscribe(
(response) => { console.log(response); }
);
}
}
【问题讨论】:
-
为了解析 CORS,您需要在服务器上允许您的来源。检查服务器上的
Access-Control-Allow-Origin,或者您可以在飞行调用的响应标头中检查。 -
如果我尝试使用 Postman 或任何浏览器访问 API,我能够获取数据。当我尝试通过我的 Ionic 应用程序访问该 API 时,问题仍然存在。 @AnandG
标签: angular ionic-framework cors ionic4