-1

I'm trying to call an API endpoint written in PHP from an Angular 7 app using http.post. However, I keep getting an error that's got me and another developer baffled.

The error is two fold. I get a 400 (Bad Request) followed by a CORS error, but at this point I think the CORS error is a red herring. I think the bad request error is the issue and it's likely something to do with how I'm making the request.

The endpoint works if I call it with Postman, and we created a separate PHP site to try and access the endpoint and that works fine. So it's clearly the Angular code.

Here's the PHP file for the API endpoint:

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

...

//get posted data
$data = json_decode(file_get_contents("php://input"));

if(!empty($data->searchby)){
    $criteria = $data->searchby;

...

        // set response code - 200 OK
        http_response_code(200);

        // show people data in json format
        echo json_encode($people);
    }
    else{
        // set response code - 404 Not found
        http_response_code(404);

        // tell the user no people found
        echo json_encode(
            array("message" => "No people found.")
        );
    }
}
// tell the user data is incomplete
else{
    // set response code - 400 bad request
    http_response_code(404);

    // tell the user
    echo json_encode(array("message" => "Failed - Missing Search Criteria", "data" => $data));
}
?>

And here's the Angular code calling the endpoint:

    let options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };

    let body = { 
      "searchby": "id",
      "id": "2",
      "email": " "
    }

    this.http.post(this.baseUrl + 'person/inq.php', body, options).subscribe(data => {
      console.log(data);
    })
  }

My guess is the issue is related to how I'm sending over the request body or the headers. All I know is if I had hair, I'd have pulled it all out by now.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Kris Kramer
  • 51
  • 1
  • 5
  • 1
    You’re right that the CORS error is a red herring — if you fix the cause of the 400 error, you‘re likely going to find that your existing CORS config is already working as expected. See the answer at https://stackoverflow.com/a/45356752/441757. The way to troubleshoot the 400 error is to look through the server logs on the API endpoint server side, and see what messages the server is logging there just prior to responding with that 400 error. – sideshowbarker Oct 17 '19 at 03:26
  • try changing **header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-`Headers`, Authorization, X-Requested-With");** to `Origin`, the part that says `Headers` – am05mhz Oct 17 '19 at 04:10
  • So, it did end up being an issue with the actual request. Once we modified some of the API code to see what was getting sent, we were able to get it working. We can't quite explain how the issue happened in the first place but the CORS part was definitely not part of it. – Kris Kramer Oct 17 '19 at 14:36

1 Answers1

0

the reason why you are not experincing an error with POSTMan is, in Angular, you are performing a XHR (XMLHTTPREQUEST) call (ajax-based), XMLHTTPREQUEST s are not allowed between cross-origins (angular project and PHP project has different origins). so need CORS configularion in server side.

sorry but i will give an exemple in .net core. (need cors nuget package for .net core). i beleive you can reflect this exemple to PHP :)

 app.UseCors(x => x.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:4200") //for development only (angular origin)
.AllowCredentials());
ratyacatnug
  • 121
  • 1
  • 5