401 (Unauthorized) [SOLVED]

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

@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);}
        );

  }

Guys

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

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

1 Like

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

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).

What should we do then?

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

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!

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

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

The answer is here

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

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

How can i solve that bug.

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);
}

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

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

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

Yes My PHP scripts is used to reply to the OPTIONS request

I am not getting exactly what you are saying @Sujan12 and @rapropos

How can i solve the issue

By using a hash function designed for this purpose, such as bcrypt.