2017-10-31 10 views
2

私はExpress REST APIにGETリクエストを行い、res.statusを200に設定してデータを返します。Angularではレスポンスにデータが含まれていますが、response.statusは常に定義されていません。アングル4 /エクスプレスでアクセス応答ステータスコード

[EDITのSTART]以下マーティンアダメックの答えから、次の

、私は私のget要求が観測ではなく、約束を使用するように、との要求に{ observe: 'response' }を含めるように変更してみました。しかし、その反応はまったく同じで、まだ応答はありませんでした。

(観察可能と)アンギュラ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 
     } 
    ) 
} 

[編集終了]

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を取得する4角:

私はアクセスすることができますどのように
router.get('/clients', (req, res) => { 
    clientService.GetClients() 
    .then((data) => { 
     res.status(204).json(data); // data is sent 
    }) 
}) 

response.statusを角度4で指定しますか?

+0

ステータスの確認方法を教えてください。いくつかのログ? –

+0

私はあなたが私の答えを試してみました。次回は私がコメントを使ってpingしているので、何かが間違っていることを知っています:]問題は、あなたが '{observe: 'レスポンス'}を3番目のパラメータとして渡していると思うが、' get'では2番目のパラメータ'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とは異なる署名を持っていることに注意してください、何もありませんこれらのメソッドの第2パラメータとして {observe: 'response'}を渡す必要があります。

関連する問題