使用角度为5.2.11的离子3。
带有标题的Angular Post无法正常工作
....
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();
}
如果没有标头,则此调用正在工作。我的目的是传球。然后它堆叠起来,最奇怪的是我没有得到任何错误。有什么想帮我的吗?
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:中
这一行不适用于8以下的Android和自定义标题:
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");