javascript - 无法从控制台日志中的 api "undefined"请求数据

标签 javascript api asynchronous get fetch

我尝试从公共(public) api 获取一些数据,但我的控制台日志中不断出现“未定义”。

这是我迄今为止尝试过的

const api_url = 'https://wger.de/api/v2/exercise/?format=json&page=29';

async function getExercises() {
    const response = await fetch(api_url);
    const data = await response.json();
    console.log(data.name);

}
getExercises();

你看到我做错了什么了吗?预先感谢您。

最佳答案

您正在尝试访问不存在的属性。 如果您将代码更改为

const api_url = 'https://wger.de/api/v2/exercise/?format=json&page=29';

async function getExercises() {
    const response = await fetch(api_url);
    const data = await response.json();
    console.log(data);

}
getExercises();

您会发现返回的响应中不包含 name 属性。

您想要做什么来获取该对象数组的名字。

const api_url= 'https://wger.de/api/v2/exercise/?format=json&page=29';

            async function getExercises(){
                const response = await fetch(api_url);
                const data = await response.json();
                console.log(data.results[0].name); // <- results is an array and each item in that array has a name property inside it.

            }
            getExercises();

要获取所有名称,您可以这样做

const api_url= 'https://wger.de/api/v2/exercise/?format=json&page=29';

            async function getExercises(){
                const response = await fetch(api_url);
                const data = await response.json();
                data.results.forEach( item => console.log(item.name))

            }
            getExercises();

关于javascript - 无法从控制台日志中的 api "undefined"请求数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60668352/

相关文章:

web-services - 如何从外部访问 joomla Controller /模型功能?

spring - 在 REST 中,我们如何处理返回资源集合的多种方式?

java - Android 中的同步任务

ios - 对于 Swift 中与闭包相关的代码,我该如何表达我的意思?

javascript - 尝试制作一个 for 循环来绘制 SVG

JavaScript 单例类型错误 : why does strict mode flag this?

javascript - 如何使用表单验证来完成多个选项?

c - Ruby C 扩展 : rb_funcall causing segfault

javascript - 异步方法总是返回未定义

javascript - 使用 jQuery 和条件的表单输入