Ionic 3 - Angular Post 与 headers 不工作

Ionic 3 - Angular Post with headers not working

将 Ionic 3 与 angular 5.2.11.

一起使用

Angular Post header 不工作

....
const header = {
        "headers": {
          "X-Custom-Header": "1",
          "X-Custom-Header2": "2"
        }
      };
...
const dt = {
  Username: this.username,
  Password: this.password
}
this.data = this.http.post('http://mydomain/json.php?f=test', JSON.stringify(dt), header);
this.data.subscribe(data => {
  this.testPass.push(data);
}, (error) => {
  this.testPass.push(error);
});

PHP 后端:

header("Content-Type: text/html; charset=utf-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');

if ($_GET["f"] == "test") {
    echo 1;
    die();
}

没有 header,此调用有效。我的目的是通过 headers。然后它堆叠起来,最奇怪的是我没有收到任何错误。 有什么想法可以帮助我吗?

const header = {
   "X-Custom-Header": "1",
   "X-Custom-Header2": "2"
}

const requestOptions = {                                                                                                                                                                                 
     headers: new Headers(header), 
};

getData() {
  return this.http.post(url, JSON.stringify(data), requestOptions);
}

来自组件的调用:

this.yourServiceFile.getData().subscribe(res => {console.log(res); });

另一种方式:

let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('X-Custom-Header', '1');
headers = headers.append('X-Custom-Header2', '2');

并将 headers 传递给您的请求。

问题出在PHP:

Android 低于 8 和自定义 headers 不接受此行:

header('Access-Control-Allow-Headers: *');

我不得不手动设置我的值:

header("Content-Type: text/html; charset=utf-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding, X-Custom-Header, X-Custom-Header2");