当响应返回200 OK

时间:2019-12-09 15:24:55

标签: angular httpclient angular2-http

我已经在api/product-search.php中创建了http://localhost/后端,如下所示:

<?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

就Angular http.js而言,似乎在许多方面都可以通过“网络”选项卡,Curl和浏览器知道的方法成功地进行了调用,因此它并不高兴,我不确定为什么。

谢谢!

2 个答案:

答案 0 :(得分:0)

这是因为您不小心将Access-Control-Allow-Origin请求标头设置为Access-Control-Request-Origin,这是无效的request header

private setHttpHeader() {
    const headers = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Access-Control-Request-Headers', '*')
      .set('Access-Control-Request-Origin', '*'); // Over here! (It should be Access-Control-Allow-Origin)
    const options = { headers: headers };
    return options;
}

此外,请注意,您实际上无法设置来自客户端的请求标头-这些标头仅应在服务器/后端上设置。

答案 1 :(得分:0)

找到了拼图的缺失部分。我在$方法上添加了inbox方法链,如下所示:

pipe()

然后返回Angular Application的响应。