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!
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)
koyaja
April 26, 2017, 3:03pm
3
I have a same problem help me
Answer is exactly the same. Make the OPTIONS call work.
koyaja
April 26, 2017, 3:47pm
5
@Sujan12
Here is my error
http://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
koyaja
April 26, 2017, 4:11pm
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
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).
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!
koyaja
April 26, 2017, 6:10pm
12
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.
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?