【发布时间】:2019-06-19 14:54:59
【问题描述】:
我尝试使用 fetch() 从https://swapi.co/ 获取数据 使用此代码,我得到未定义,但在 chrome 的“网络”部分中,我看到了我需要的数据。我如何访问它?
fetch('https://swapi.co/api/people/1/')
.then(resp => resp.json)
.then(obj => console.log(obj));
【问题讨论】:
我尝试使用 fetch() 从https://swapi.co/ 获取数据 使用此代码,我得到未定义,但在 chrome 的“网络”部分中,我看到了我需要的数据。我如何访问它?
fetch('https://swapi.co/api/people/1/')
.then(resp => resp.json)
.then(obj => console.log(obj));
【问题讨论】:
您好,这将获取以 json 格式返回的数据
fetch('https://swapi.co/api/people/1')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
【讨论】:
如果你有正确的环境来调用 fetch API,那么可能有 2 个结果
您将获得正确的结果数据
你会得到一个错误
fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
// Your code for handling the data you get from the API
})
.catch (function() {
// This is where you run code if the server returns any errors
});
使用 catch 查看您的请求出了什么问题
【讨论】: