Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/407.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用JSON和fetch API_Javascript_Json_Fetch Api - Fatal编程技术网

Javascript 使用JSON和fetch API

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())

我正在尝试使用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())
    .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,非常好的帖子。