1

I have the following Authentication and Login service in Angular 6:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})

export class AuthApiService {
  public credentials:any=[];
  constructor(private http: HttpClient) { }


  login(username, password)
  {
    let headerOptions = new HttpHeaders();
    headerOptions.append('Content-Type', 'application/json');
    headerOptions.append("authorization", "basic aGM0YXBwOmHjddP5NjU=");
    let test = {user: username, pass: password};
    this.credentials = JSON.stringify(test);
    console.log("hi "+ this.credentials);
    return this.http.post('https://127.0.0.1/api/scripts/login.php', this.credentials, {
      headers: headerOptions
    }).pipe(map(
        res=>{
          console.log(res)
        },
        err=>
          console.log(err)
      ))
  }
}

And when I click on Login Button:

a id="btn-login"  (click)="login()" class="btn btn-success">Login </a>

A function in login.component.ts will execute the login function of the Authentication service:

login(){
    this.auth.login("a", "p").subscribe(
      (data)=>{
        console.log(data)
      },
      (error)=>{
        console.log(error)
      }
    )
}

In php, and for the url, I am running it in the browser and I can see the result properly 1, but there is an error at the console when I click on the button:

"Http failure response for (unknown url): 0 Unknown Error"

enter image description here

At the network tab:

enter image description here

The PHP script:

Lets start with the main class:

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
header('Access-Control-Allow-Headers: *');

error_reporting(E_ALL);

class api {
    private $username ="...";
    private $password ="...";
    private $db="...";
    private $host = "...";

    public $conn;

    //Connection

    public function connection(){
        try{
            $this->conn = new PDO("mysql:host=$this->host;dbname=$this->db", $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->conn->exec("SET CHARACTER SET utf8");

            return $this->conn;
        }
        catch(PDOException $e){
            return $e->getMessage();
        }

    }

    //Login

    public function login($conn, $user){
        $login = "SELECT username FROM login WHERE username=:user LIMIT 1";
        $execLogin = $this->conn->prepare($login);
        $execLogin->bindValue(":user", $user);
        $execLogin->execute();
        $res = $execLogin->rowCount();

        return $res;
        // if($res>0)
        // {
        //     return json_encode($res);
        // }
        // else{
        //     echo 0;
        // }
    }

}

?>

And then, the login function is executed (https://127.0.0.1/api/scripts/login.php):

<?php
header('Content-Type: application/json');

require_once('../api.php');

//Getting username and password from Ionic
$user="brital";
$pass = json_decode($_POST['credentials']);

$newApi = new api();
$conn = $newApi->connection();
$res = $newApi->login($conn, $user);
echo $res;
?>
hlovdal
  • 26,565
  • 10
  • 94
  • 165
alim1990
  • 4,656
  • 12
  • 67
  • 130
  • 1
    If you try it with Postman, does it work? Do you have CORS set up correctly? also see [this possible duplicate](https://stackoverflow.com/questions/47180634/i-get-http-failure-response-for-unknown-url-0-unknown-error-instead-of-actu) – Grenther Jul 12 '18 at 12:28

1 Answers1

1

Looks like you are using https, and my guess is this is a self signed certificate? Then it is likely the same issue as mentioned here: angular and self-signed SSL cert - ERR_INSECURE_RESPONSE

Ionic/Angular's "0 Unknown Error" can have many reasons. It could be a CORS issue as another comment mentioned, but it seems you are already setting the headers correctly.

You can confirm it's a certificate issue by browsing the URL (in your case "https://127.0.0.1/api/scripts/login.php") directly in Chrome. Do you get the error "NET::ERR_CERT_AUTHORITY_INVALID"?

The (temp) solution is as mentioned in the link - proceed to the unsafe option so Chrome remembers to accept your self signed cert. The proper way is of course to use a real certificate.

Ken Goh
  • 1,049
  • 11
  • 8