Ionic get data from PHP API with authentication basic (Status Code: 401 Authorization Required)


#1

Hello everyone, I got this error on request data to PHP API with authentication basic
this my authService.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = "http://192.168.1.168/api/";

@Injectable()
export class AuthServiceProvider {

  constructor(public http: Http) {
    console.log('Hello AuthServiceProvider Provider');
  }

  postData(credentials, type) {
    return new Promise((resolve, reject) => {
      let headers = new Headers();
      headers.append('Access-Control-Allow-Origin', '*');
      headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
      headers.append('Accept', 'application/json');
      headers.append('content-type', 'application/json');
    
      headers.append('Authorization', 'Basic YWRtaW46YWRtaW4=');

      console.log(headers);
      this.http.post(apiUrl + type, JSON.stringify(credentials), { headers: headers }).
        subscribe(res => {
          resolve(res.json());
        }, (err) => {
          reject(err);
        });
    });
  }

}

and this my PHP API

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

$AUTH_USER = 'admin';
$AUTH_PASS = 'admin';

$has_login_header = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW']));
if ($has_login_header && $_SERVER['PHP_AUTH_USER'] == $AUTH_USER && $_SERVER['PHP_AUTH_PW'] == $AUTH_PASS) {
    
    echo '{"error":{"text":"You are authorized"}';
} else {
    header('HTTP/1.1 401 Authorization Required');
    header('WWW-Authenticate: Basic realm="Access denied"');
    echo '{"error":{"text":"Auth err."}';
    exit;
}


?>

But I got this error


Please help me