401 (Unauthorized) [SOLVED]


#1

Hi, friends!
When consuming the service it displays the following error:


http://localhost:8080/Api/webresources/v1/usuario/mguillen. Response for preflight has invalid HTTP status code 401 (Unauthorized)

ApiRest.ts

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

@Injectable()
export class ApiRest {

  constructor(public http: Http) {
    
  }

  public getUsuarioInventiva(usuario: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Basic dXN1YXJpb09wZW5UZWNoOm9wZW5UZWNoJkRlbFNvbDE5OTUyMDE2');
    let options = new RequestOptions({ headers: headers });
    let baseURL = "http://localhost:8080/Api/webresources/v1/usuario/";
    return this.http.get(baseURL + usuario, options)
      .map(res => res.json());
  }

}

Registro.ts

public getUsuarioInventiva() {
    this.api.getUsuarioInventiva('mguillen').subscribe(data => {
      console.log(data.nombre);
    });
  }

Postman

Thanks!


How to solve this error angular http
#2

Replace the “GET” in Postman with “OPTIONS” to simulate this “Preflight request” (google this to find out more what exactly this is, tldr: Security). So make your PHP script respond to this OPTIONS request with a 200 OK and you are one step further.

(You can also check the developer tools network tab to see this preflight request in your browser)


#3

I have a same problem help me


#4

Answer is exactly the same. Make the OPTIONS call work.


#5

@Sujan12
Here is my errorhttp://localhost:9090/rest/entrypoint/branches/ 401 (Unauthorized)
this code is`

   var token='06a91668-9e6c-4ac0-9566-830c30720150';
      let header = new Headers();
    let    contentHeader = new Headers({"auth-token": "06a91668-9e6c-4ac0-9566-830c30720150"}).toJSON;
       header.append('Auth-Token',token);
       header.append("Content-Type","application/json");
       // header.append("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
 //let headers = new Headers({ 'Authorization': 'Bearer ' + token });
        let options = new RequestOptions({ method:"GET",headers: header,url:"http://localhost:9090/rest/entrypoint/branches/" });
        console.log(options);
 this.http.get(`http://localhost:9090/rest/entrypoint/branches/`,contentHeader).map(res => res.json())
        .subscribe(
          data => {this.branche = data
          console.log(data);},
          err => {err=err
           console.log(err);}
        );

  }

#6

Guys

if(request method === "OPTIONS") {
   respond 200 OK
}

Though I’m not sure why you have a preflight for a GET request o.o


#7

here is a code whithout comment
the use is a gatway and required token

getbranche{
   
      let header = new Headers();

    let    contentHeader = new Headers({"auth-token": "06a91668-9e6c-4ac0-9566-830c30720150"});
      
 this.http.get(`http://localhost:9090/rest/entrypoint/branches/`,contentHeader).map(res => res.json())
        .subscribe(
          data => {this.branche = data
          console.log(data);},
          err => {err=err
           console.log(err);}
        );

  }

XMLHttpRequest cannot load http://localhost:9090/rest/entrypoint/branches/. Response for preflight has invalid HTTP status code 401


#8

The problem is not your Ionic code but whatever is running on http://localhost:9090/rest/entrypoint/branches/ - it has to answer with a 200 OK to a OPTIONS request (and not a GET request).


#9

What should we do then?


#10

Fix your code at http://localhost:9090/rest/entrypoint/branches/.


#11

I have solved it with:
Adding proxies in ionic.config.json

{
  "name": "AuditoriaVentaSds",
  "app_id": "",
  "v2": true,
  "typescript": true,
  "proxies": [
    {
      "path": "/v1",
      "proxyUrl": "http://localhost:8080/Api/webresources/v1"
    }
  ]
}

ApiRest.ts

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

@Injectable()
export class ApiRest {

  constructor(public http: Http) {
    
  }

  public getUsuarioInventiva(usuario: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Basic dXN1YXJpb09wZW5UZWNoOm9wZW5UZWNoJkRlbFNvbDE5OTUyMDE2');
    let options = new RequestOptions({ headers: headers });
    let baseURL = "/v1/usuario/";
    return this.http.get(baseURL + usuario, options)
      .map(res => res.json());
  }

}

Regards!


#12

The problem is that it is an api that provide me the url


#13

Then tell whoever is in charge of that API that you have a CORS problem with it.


#14

The answer is here


#15

I try all the things.But still i get error…please provide solution.


#16

Your OPTIONS request is returning an error 401. It should not do that.


#17

How can i solve that bug.


#18

and after i try some other code it give error like

Failed to load http://localhost/jainsangh/view/view_occupation.php: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8101’ is therefore not allowed access.

but in my api i m inlcude in header


<?php
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Allow-Origin: *');
include '../class/authweb.php';
include '../class/connection.php';

$pdata = file_get_contents("php://input");

$data = json_decode($pdata);

$con = connect();
if ($_SERVER['PHP_AUTH_USER'] == $username && $_SERVER['PHP_AUTH_PW'] == $password) 
{
    $q = mysqli_query($con, "Select * from occupation where is_active=1 and is_delete=0")or die(mysqli_error($con));

if (mysqli_num_rows($q) > 0) {
    $response["occupation_array"]= array(); //empty array
    while ($row = mysqli_fetch_assoc($q)) {
        array_push($response["occupation_array"], $row);
    }
    
    $response["success"] = "1";
    //echo $row;
} else {
    $response["success"] = "0";
}
echo json_encode($response);
}

#19

Please tell use you’re not storing plaintext passwords on your server.


#20

Obviously not - otherwise you wouldn’t get this error:

Your PHP scripts is used to reply to the OPTIONS request?