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.