2017-07-22 24 views
0

我正在設置一個非常基本的反應應用程序,並試圖調用我的本地主機服務器(單獨的後端服務器),其上有JSON數據。我想提取從承諾返回的數據,但我沒有做的似乎工作。這裏是我的代碼:如何從React中獲取諾言中的響應數據?

fetch('http://localhost:8080/posts') 
    .then(function(response) { 
     const items = response.json() 
     console.log(items) 
    }) 

我已經試過response.json(),response.body,我試圖登錄身上帶。然後(函數的(身體){執行console.log(身體)}),響應。數據,response.body,但沒有任何工作。這裏是控制檯打印出了什麼:

enter image description here

我怎樣才能把它是給我的輸出,並把它在一個數組,我可以遍歷? 「內容」和「ID」是我需要訪問的內容。

和FYI,數組,當我去到本地主機:8080 /帖子在我的瀏覽器很簡單:

[{"id":1,"content":"hello, this is post 1"}] 

任何幫助表示讚賞,謝謝!

+0

什麼是你的控制檯打印出來 – Kermit

+0

,我把代碼,常數項= response.json() 的console.log(項目)的代碼,產生打印出來,我把在圖像中。 – joey

+0

response.data打印「undefined」 – joey

回答

3

致電response.json()也將返回一個承諾,所以你也需要處理。嘗試下面的代碼。

fetch('http://localhost:8080/posts') 
.then(function(response){ return response.json(); }) 
.then(function(data) { 
    const items = data; 
    console.log(items) 
}) 
+0

是的,這是正確的。非常感謝! – joey

相關問題