ionic 3 HttpClient get status + send headers
Asked Answered
P

2

1

i'm using the HttpClientModule on ionic 3, and i want to do a get on my api

let email = "[email protected]";
let password = "password";
    let headers = new HttpHeaders();
    this.http.get('http://127.0.0.1:8000/api/login',{
      headers: {'email':email,'password':password}
   });

i don't want to get the json but only the status of the request, for doing something like :

if(status == 200) { ... }
esle { ... } 

can you guys please help me ?

Thank you

Pungent answered 29/5, 2018 at 19:54 Comment(1)
See: angular.io/guide/http#reading-the-full-responseCamus
A
2

Add observe : 'response' in header options of http.get method and subscribe to get() method to get response status whatever you want..

this.http.get('http://127.0.0.1:8000/api/login',{
      headers: {'email':email,'password':password},observe: 'response'
   }).subscribe(
    res => { console.log(res) ;

             if(res.status==201)
             {
                 //do action
             }else
             {
             }
          },
Actinochemistry answered 30/5, 2018 at 10:41 Comment(3)
it's not working, i'm on ionic 3, it's problably the main reason I got this on my console : - OPTIONS http://127.0.0.1:8000/api/login 403 (Forbidden) - Failed to load http://127.0.0.1:8000/api/login: 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:8100' is therefore not allowed access. The response had HTTP status code 403. Pungent
ok sorry, the code is working, the error come from this line : No 'Access-Control-Allow-Origin' header is present on the requested resource.Pungent
the code is probably working, but my ionic is on the port 8100 , and my api is on the port 8000, so i have the error : No 'Access-Control-Allow-Origin' header is present on the requested resource. Pungent
C
0

You have to use observe: 'response' as you second parameter in the Get request of httpClientModule like this -

this.http.get('http://127.0.0.1:8000/api/login',{
      headers: {'email':email,'password':password},
      observe: 'response'
   }

observe : 'response' for complete response.

observe : 'body' for response with body.

observe : 'events' for response with events. For more details on this refer here

Cat answered 29/5, 2018 at 20:7 Comment(1)
thank you for the response, but it's not working for me, my code is : this.http.get('http://127.0.0.1:8000/api/login',{ headers: {email:'[email protected]',password :'chenet'}, observe: 'response' }).subscribe( response => { console.log(response); }, err => { console.log(err); }); but this return an error.. On postman, i can doing my request get, send the headers, and i got a 200 status, i just want get the status after the getPungent

© 2022 - 2024 — McMap. All rights reserved.