2017-10-31 1 views
2

Express REST API에 GET 요청을하고 res.status를 200으로 설정 한 후 데이터를 반환합니다. Angular에서 응답에는 데이터가 있지만 response.status는 항상 정의되지 않습니다. . 아래 마틴 ADAMEK의 대답에서 다음 각도 4/Express의 응답 상태 코드

[편집 START]

, 나는 약속보다는 관찰 가능한을 사용하고, 요청 { observe: 'response' }을 포함하는 내 GET 요청을 변경했습니다. 그러나 응답은 똑같습니다. 여전히 응답이 없습니다. 상태. (관찰 가능한 포함)

각도 4 GET

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

[편집 END]

각도 4

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

익스프레스 API 얻을 :

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

가 어떻게 액세스 할 수 있습니다 각도 4의 response.status?

+0

상태를 확인하는 방법을 보여줄 수 있습니까? 어떤 기록들? –

+0

나는 내 대답을 시도했다. 다음 번에 코멘트를 통해 ping을하면 뭔가 잘못되었다는 것을 알 수 있습니다.] 문제는 여러분이'{observe : '응답'} '을 세 번째 매개 변수로 전달하고 있지만'get'에 대해서는 두 번째 매개 변수로 'payload'가 없습니다. –

+0

Btw 이것은 관측 가능/약속에 관한 것이 아니므로 원하는 경우 약속을 지키십시오. 중요한 부분은이 옵션을 추가하여 'body'대신 전체 응답을 얻을 수 있도록하는 것입니다. –

답변

1

HttpClient은 페이로드를 JSON에서 자동으로 변환하여 전달합니다. 당신이 전체 응답 개체에 액세스하려는 경우, 당신은이 작업을 수행 할 수 있습니다 또한

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

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

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

GETDELETE 방법 POSTPUT과 다른 서명이 있습니다, 더는 없다 페이로드 매개 변수이므로 해당 메소드의 두 번째 매개 변수로 {observe: 'response'}을 전달해야합니다.