【发布时间】:2020-04-02 17:39:09
【问题描述】:
我在http://localhost/ 中创建了我的api/product-search.php 后端,如下所示:
<?php
header('Access-Control-Allow-Origin', '*');
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Request-Headers: *");
header("Access-Control-Request-Method", "GET, POST, PUT, DELETE, OPTIONS");
Header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
header('Content-type: application/json');
$myObj->name = "Test Product";
$myObj->qty = 30;
$myObj->sku = "test-p";
$myJSON = json_encode($myObj);
echo $myJSON; echo PHP_EOL;
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
?>
像这样使用来自http://localhost:4200/的Angular HttpClient:
getProducts(): Observable<any> {
return this.http.get(`http://localhost/api/product-search.php`, this.setHttpHeader());
}
private setHttpHeader() {
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Access-Control-Request-Headers', '*')
.set('Access-Control-Request-Origin', '*');
const options = { headers: headers };
return options;
}
ngOnInit() {
this.getProducts().subscribe(
response => {
// alert('Response');
console.log(response);
},
error => {
// alert('Error');
console.log(error);
}
);
}
当我检查控制台时,我收到以下错误: Angular HttpClient Request
当我检查网络选项卡时,我得到 200 OK,如下所示: Browser Network Tab
我也可以卷曲成功:
curl -i http://localhost/api/product-search.php
HTTP/1.1 200 OK
Date: Mon, 09 Dec 2019 15:16:37 GMT
Server: Apache/2.4.34 (Unix) PHP/7.1.23
X-Powered-By: PHP/7.1.23
Access-Control-Request-Headers: *
Access-Control-Allow-Origin: *
Content-Length: 100
Content-Type: application/json
{"name":"Test Product","qty":30,"sku":"test-p"}
Host: localhost
User-Agent: curl/7.54.0
Accept: */*
在 Chrome 中: Google Chrome Browser
就“网络”选项卡、Curl 和浏览器而言,看起来呼叫在许多方面都成功了,因为 Angular http.js 不是这样,所以它不开心,我不知道为什么。
提前致谢!
【问题讨论】:
-
你能不能显示错误
-
您是否订阅了来自服务器的回复? getProducts().subscribe((value) => {//dummy})
-
@Alann Yes 更新了它
-
查看 MDN 文档为“
Access-Control-Request-Origin”生成了no results。你的意思是Access-Control-Allow-Origin,只能在后端/服务器上设置,不能在客户端设置(如上一个错误所示)? -
另外,请考虑复制和粘贴您的错误日志,而不是附上它的屏幕截图,以便更容易搜索和为互联网连接不佳的用户提供。
标签: angular httpclient angular2-http