最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the response data from promise in React? - Stack Overflow

programmeradmin4浏览0评论

I am setting up a very basic react app, and trying to call my local host server (separate backend server), which has JSON data on it. I want to extract the data returned from the promise, but nothing I do seems to work. Here is my code:

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

I have tried response.json(), response.body, I tried logging the body with .then(functio(body) { console.log(body)}), response.data, response.body, but nothing works. Here is what the console prints out:

How can I take the output it is giving me, and get it in an array that I can iterate through? The "content" and "id" are what I need access to.

and FYI, the array, when i go to localhost:8080/posts in my browser is simple:

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

any help is appreciated, thanks!

I am setting up a very basic react app, and trying to call my local host server (separate backend server), which has JSON data on it. I want to extract the data returned from the promise, but nothing I do seems to work. Here is my code:

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

I have tried response.json(), response.body, I tried logging the body with .then(functio(body) { console.log(body)}), response.data, response.body, but nothing works. Here is what the console prints out:

How can I take the output it is giving me, and get it in an array that I can iterate through? The "content" and "id" are what I need access to.

and FYI, the array, when i go to localhost:8080/posts in my browser is simple:

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

any help is appreciated, thanks!

Share Improve this question asked Jul 22, 2017 at 15:39 jjjjjjjjjjjjjjjj 4,50313 gold badges58 silver badges75 bronze badges 3
  • what's code of your console print out – Kermit Commented Jul 22, 2017 at 15:48
  • the code that I put, const items = response.json() console.log(items), yields the print out that I put in the image. – jjjjjjjj Commented Jul 22, 2017 at 15:49
  • response.data prints "undefined" – jjjjjjjj Commented Jul 22, 2017 at 15:50
Add a ment  | 

1 Answer 1

Reset to default 11

The call toresponse.json()will also return a promise so you need too handle that also. Try the code below.

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

评论列表(0)

  1. 暂无评论