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
1 Answer
Reset to default 11The 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)
})