Javascript 使用JSON和fetch API
我正在尝试使用fetch API在javaScript代码中获取此JSON:Javascript 使用JSON和fetch API,javascript,json,fetch-api,Javascript,Json,Fetch Api,我正在尝试使用fetch API在javaScript代码中获取此JSON: { "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ] } 这是我的代码: const endpoint = 'http://localhost:3000/posts' let posts = [] fetch(endpoint) .then(resp => resp.json())
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
]
}
这是我的代码:
const endpoint = 'http://localhost:3000/posts'
let posts = []
fetch(endpoint)
.then(resp => resp.json())
.then(data => posts.push(...data))
console.log(posts[0])
console.log在chrome的控制台上给了我未定义的内容,但是如果我在同一控制台上键入posts[0],我会得到我希望得到的post对象。
我正在使用JSON服务器提供JSON文件,使用vs代码扩展名live server提供.html。“我正在尝试获取此JSON…”该JSON无效。它是对象初始值设定项的内部,但它需要外部(例如
{}
,例如{“posts:[…]}
)。然而,这里的主要问题是fetch
是异步的,因此posts
在您记录它时仍然是空的(稍后,当fetch完成时,条目将被添加到其中)。还请注意,您没有检查您需要执行的。ok
;详细信息请参见。在之前执行控制台.log
语句。然后(data=>posts.push(…data))
,您应该了解异步函数的工作原理。谢谢@T.J.Crowder,非常好的帖子。