Ionic 3 – Angular Post with headers not working

Issue

Using Ionic 3 with angular 5.2.11.

Angular Post with headers not working

....
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 backend:

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();
}

Without a header, this call is working. My purpose is to pass the headers. Then it stacks and the weirdest is that I don’t get any error.
Any thoughts to help me?

Solution

The problem was in PHP:

This line is not accepted for Android below 8 and for custom headers:

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

I had to put my values manually:

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");

Answered By – Vasilis Greece

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.