如何在JavaScript对象中存储Fetch API JSON响应
我想将获取API JSON存储为JavaScript对象,以便在其他地方使用它。console.log测试正常,但我无法访问数据 以下工作:它显示具有三个待办事项的控制台条目:如何在JavaScript对象中存储Fetch API JSON响应,javascript,json,api,fetch-api,Javascript,Json,Api,Fetch Api,我想将获取API JSON存储为JavaScript对象,以便在其他地方使用它。console.log测试正常,但我无法访问数据 以下工作:它显示具有三个待办事项的控制台条目: fetch('http://localhost:3000/api/todos') .then(data => data.json()) .then(success => console.log(success)); 以下操作不起作用: fetch('http://localhost:300
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));
如果我尝试访问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));
fetch('http://localhost:3000/api/todos')
.then(res=>res.json())
。然后(数据=>{
让输出=“”;
data.forEach(函数(todo){
输出+=`
- ID:${todo.ID}
- 标题:${todo.Title}
- IsDone:${todo.IsDone}
`;
});
document.getElementById('ToDoList')。innerHTML=output;
返回输出;
})
.catch(err=>console.log('出现了问题:',err));
但是,我不能手动更新内部HTML;我需要该对象来执行其他用户体验。您可以使用异步等待,如下所示
async function consumingFunc () {
let response = await fetch('http://localhost:3000/api/todos')
console.log(response)
}
consumingFunc()
您还可以使用如下功能:
function doSomething(success){
//do whatever you like
}
fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => doSomething(success));
您可以在外部声明一个变量,然后像这样将结果分配给它
var yourTodos;
fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => yourTodos = success);
然后将
yourTodos
作为javascript对象,您可以随意使用它。success=>JSON.parse(success)
,如果这对您有帮助的话。请选择我的答案作为正确答案。提前谢谢。