Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Response Status Code in Angular 4 / Express

I'm making GET requests to an Express REST API, and returning data after setting res.status to 200. In Angular the response contains the data, but response.status is always undefined.

[EDIT START]

Following from Martin Adámek's answer below, I tried changing my get request to use an Observable rather than a Promise, and to include { observe: 'response' } in the request. But the response was exact the same - still no response.status.

Angular 4 get (with Observable)

requestNew(endPoint:string, type:string, query:string, data:any) {
  this.http[type](this.configService.apiHost + endPoint + query, data ? data : '', { observe: 'response' })
    .subscribe(
      (response:HttpResponse<any>) => {
        console.log(response) // Array containing expected data
        console.log(response.status) // undefined
      }
    )
}

[EDIT END]

Angular 4 get

import { HttpClient, HttpResponse, HttpErrorResponse } from '@angular/common/http';

request(endPoint:string, type:string, query:string, data:any) {
  let promise = new Promise((resolve, reject) => {
    this.http[type](this.configService.apiHost + endPoint + query, data ? data : '')
      .toPromise()
      .then((response: HttpResponse<any>) => {
        resolve(response);
      })
      .catch((error: HttpErrorResponse) => {
      })
  });
  return promise;
}

Express API:

router.get('/clients', (req, res) => {
  clientService.GetClients()
    .then((data) => {
      res.status(204).json(data); // data is sent
    })
})

How can I access response.status in Angular 4?

like image 684
Runny Yolk Avatar asked Oct 29 '25 15:10

Runny Yolk


1 Answers

HttpClient will automatically convert the payload from JSON and pass it to you. If you want to access the whole response object, you can do this:

http
  .get('/data.json', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.status);
  });

https://angular.io/guide/http#reading-the-full-response

https://angular.io/api/common/http/HttpResponse

Also note that GET and DELETE methods have different signature than POST and PUT, there is no payload parameter so you need to pass {observe: 'response'} as second parameter for those methods.

like image 164
Martin Adámek Avatar answered Oct 31 '25 06:10

Martin Adámek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!