0

I am tasked with connecting to an old php login api which simply returns a success or error message response object.

When I connect with the correct credentials I receive the success object and when do not I receive the error. Great!

However, httpClient does not seem to be recognizing the error object. Therefore, the object is accepted as a successful response object regardless of whether it is or it isn't.

The two relevant lines of php code:

$response = array("error" => "Combinación user-pass errónea", "success" => false, "status" => 500, "message" => "Error");
echo $json_response = safe_json_encode($response);

I then added a couple more properties to the error response in the hope of it being recognized:

$response = array("error" => "Combinación user-pass errónea", "success" => false, "status" => 403, "message" => "Error");

No luck...

I have then converted the observable into a promise so as to make the process as close as possible to the code used on an AngularJS app which uses the same login api:

let httpOptions = {
  headers: new HttpHeaders(
    { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }),
};

let params = new HttpParams({
  fromObject: { action: "login", username: credentials.username, password: credentials.password },
});

this.httpClient.post(`http://xxxxxxxxxxx/user_controller.php`, params.toString(), httpOptions).toPromise()
.then( data => console.log(data),
        err => console.log(err) );

Still no luck...

jamesbcn
  • 307
  • 4
  • 6
  • 20
  • "However, httpClient does not seem to be recognizing the error object." Are you setting the HTTP response code to indicate an error condition? – miken32 Jun 25 '21 at 19:05

1 Answers1

1

The $http.error handler is triggered by server errors like 500 or 401; If you wish to trigger a 401 error (unauthorized) for a bad login, do this:

if ($loginFailed) {
  header("HTTP/1.1 401 Unauthorized");
  exit;
}

Your angular code will pick that up as an error.

If you want to go on sending errors back the way you are currently, pick them up in the success callback, since the call was actually successful according to the server.

this.httpClient.post(`http://xxxxxxxxxxx/user_controller.php`, params.toString(), httpOptions).toPromise()
.then( data => { 
    console.log(data); 
    if (JSON.parse(data).error) this.triggerErrorResponse(data.error); 
  }, err => console.log(err) );
Kinglish
  • 23,358
  • 3
  • 22
  • 43