我正在设置一个非常基本的 react 应用程序,并尝试调用我的本地主机服务器(单独的后端服务器),它上面有 JSON 数据。我想提取从 promise 返回的数据,但我所做的一切似乎都不起作用。这是我的代码:
fetch('http://localhost:8080/posts')
.then(function(response) {
const items = response.json()
console.log(items)
})
我尝试过 response.json()、response.body,我尝试使用 .then(functio(body) { console.log(body)})、response.data、response.body 记录正文,但没有任何效果。以下是控制台打印的内容:
如何获取它给我的输出,并将其放入一个可以迭代的数组中? “内容”和“id”是我需要访问的。
仅供引用,当我在浏览器中访问 localhost:8080/posts 时,数组很简单:
[{"id":1,"content":"hello, this is post 1"}]
任何帮助表示赞赏,谢谢!
最佳答案
调用 response.json()
也会返回一个 promise ,所以你也需要处理它。试试下面的代码。
fetch('http://localhost:8080/posts')
.then(function(response){ return response.json(); })
.then(function(data) {
const items = data;
console.log(items)
})
关于javascript - 如何从 React 中的 Promise 中获取响应数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45256329/