无法访问 fetch API 请求的结果
我一直试图从我的 fetch API 请求中访问数组结果。我可以获取要返回的结果并将其从 JSON 解析为 JavaScript 对象。但是我无法访问结果。返回的数组称为结果。我想知道我错过了什么。该项目的最终目标是从 API 中获取 12 个随机配置文件并将其显示在卡片 div 上。我收到的错误消息是:
'Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at app.js:40'
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Public API Requests</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="css/normalize.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<header>
<div class="header-inner-container">
<div class="header-text-container">
<h1>AWESOME STARTUP EMPLOYEE DIRECTORY</h1>
</div>
<div class="search-container">
</div>
</div>
</header>
<div id="gallery" class="gallery">
</div>
</body>
<script type="text/javascript" src="app.js"></script>
</html>
Javascript
const gallery = document.getElementById('gallery');
const card = document.createElement('div');
card.classList.add('card');
gallery.appendChild(card);
function fetchData(url) {
return fetch(url)
.then(response => { return response.json()})
.then(data => {console.log(data)})
.catch(error => {console.log('Error with fetching API', error)})
}
function generateInfo(data) {
const info = data.map( item => `
<div class="card-img-container">
<img class="card-img" src="${data}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${name.first} ${name.last}</h3>
<p class="card-text">${data.email}</p>
<p class="card-text cap">${location.city}</p>
</div>
`)
card.innerHTML = info;
}
fetchData('https://randomuser.me/api/')
.then(data => generateInfo(data.results));
错误很明显,您在
data
中获取的对象未定义,这就是它没有
result
键的原因。
检查数据是否来自 URL。当我获取 URL 时,有 JSON 传入。
另请注意,在用于调试的第二个
then
中没有返回
data
变量,这就是您之后什么也得不到的原因。
添加返回语句,如:
return data;
来自文档的与
catch
部分相关的额外信息:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
如果您想检查错误,请查看响应中的状态代码。
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
更改 fetchData 函数,删除获取最终数据的 .then 块,在调用 fetchData 时附加它<​​/p>
function fetchData(url) {
return fetch(url)
.then(response => { return response.json()})
.catch(error => {console.log('Error with fetching API',
error)})}
fetchData('https://randomuser.me/api/')
.then(data =>generateInfo(data.results)); //success to the final promise
现在在生成信息中使用 foreach() 而不是 map()。因为您需要为每个用户对象创建卡片。
function generateInfo(results) {
results.forEach( userObj =>{
const card = document.createElement('div');
card.classList.add('card');
card.innerHTML = `
<div class="card-img-container">
<img class="card-img" src="${userObj.picture.thumbnail}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${userObj.name.first} ${name.last}</h3>
<p class="card-text">${userObj.email}</p>
<p class="card-text cap">${userObj.location.city}</p>
</div>
`;
gallery.appendChild(card);
})
}
const gallery = document.getElementById('gallery');
function fetchData(url) {
return fetch(url)
.then(response => { return response.json()})
.catch(error => {console.log('Error with fetching API', error)})}
function generateInfo(results) {
results.forEach( userObj =>{
const card = document.createElement('div');
card.classList.add('card');
card.innerHTML = `
<div class="card-img-container">
<img class="card-img" src="${userObj.picture.thumbnail}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${userObj.name.first} ${name.last}</h3>
<p class="card-text">${userObj.email}</p>
<p class="card-text cap">${userObj.location.city}</p>
</div>
`;
gallery.appendChild(card);
})
}
fetchData('https://randomuser.me/api/')
.then(data =>generateInfo(data.results));
<header>
<div class="header-inner-container">
<div class="header-text-container">
<h1>AWESOME STARTUP EMPLOYEE DIRECTORY</h1>
</div>
<div class="search-container">
</div>
</div>
</header>
<div id="gallery" class="gallery">
</div>