如何在JavaScript对象中存储Fetch API JSON响应

问题描述 投票:-1回答:3

我想将Fetch API JSON存储为JavaScript对象,因此我可以在其他地方使用它。 console.log测试有效,但我无法访问数据。

以下作品:它显示具有三个待办事项的控制台条目:

 fetch('http://localhost:3000/api/todos')
    .then(data => data.json())
    .then(success => console.log(success));

以下不起作用:

fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => JSON.parse(success));

如果我尝试访问成功,它不包含任何数据。

尝试过console.log,它有效。

还试过以下,有效:

fetch('http://localhost:3000/api/todos')
    .then(res => res.json())
    .then(data => {
        let output = '';
        data.forEach(function (todo) {
        output += `
            <ul>
                <li>ID: ${todo.id}</li>
                <li>Title: ${todo.title}</li>
                <li>IsDone: ${todo.isdone}</li>
            </ul>
            `;
        });
        document.getElementById('ToDoList').innerHTML = output;
        return output;
    })
    .catch(err => console.log('Something went wrong: ', err));

但是,我无法手动更新内部HTML;我需要该对象来做其他UX。

javascript json api fetch-api
3个回答
1
投票

您还可以使用以下功能:

 function doSomething(success){
   //do whatever you like
 }

 fetch('http://localhost:3000/api/todos')
    .then(data => data.json())
    .then(success => doSomething(success));

0
投票

您可以使用async await,如下所示

async function consumingFunc () {
  let response = await fetch('http://localhost:3000/api/todos')
  console.log(response)
}

 consumingFunc()

0
投票

您可以在外部声明一个变量,并将结果分配给它

var yourTodos;

fetch('http://localhost:3000/api/todos')
    .then(data => data.json())
    .then(success => yourTodos = success);

然后你有yourTodos作为你的javascript对象,你可以使用任何你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.