[英]Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined
I am trying to fetch data form OMDB database to dispaly movies. 我正在尝试从OMDB数据库中获取数据以显示电影。 Initially I have implemented click event to call data and no errors were found.
最初,我实现了click事件以调用数据,但未发现任何错误。 But when i switch to keyup event i got this error.
但是当我切换到keyup事件时,出现此错误。
Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined at fetchMovie.getMovies.then.res (main.js:27) fetchMovie.getMovies.then.res @ main.js:27 async function (async) searchInput.addEventListener @ main.js:19 未捕获(承诺)TypeError:无法读取fetchMovie.getMovies.then.res(main.js:27)上未定义的属性'forEach'@ fetchMovie.getMovies.then.res @ main.js:27异步函数(异步)searchInput。 addEventListener @ main.js:19
let searchInput = document.getElementById('search')
class fetchData {
constructor() {
this.apiKey = 'here is APIKey'
}
async getMovies(movie) {
const movieRes = await fetch(`http://www.omdbapi.com/?apikey=${this.apiKey}&s=${movie}`)
const moveData = await movieRes.json()
return {
moveData
}
}
}
const fetchMovie = new fetchData
searchInput.addEventListener('keyup', (e) => {
let input = e.target.value
if (input !== '') {
fetchMovie.getMovies(input)
.then(res => {
let data = res.moveData.Search
let output = ''
data.forEach(movie => {
output += `
<div class="col-md-3">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="${movie.Poster}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">${movie.Title}</h5>
<p class="card-text">${movie.Year}</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>`
});
document.getElementById('container').innerHTML = output;
})
}
e.preventDefault();
})
SCEENSHOT 场景拍摄
ERROR fixed with empty images also added keyup event. 错误修正为空白图片,还添加了keyup事件。 No errors in console
控制台中没有错误
let searchInput = document.getElementById('search');
class fetchData {
constructor() {
this.apiKey = '884df292'
}
async getMovies(movie) {
const movieRes = await fetch(`http://www.omdbapi.com/?apikey=${this.apiKey}&s=${movie}`)
const moveData = await movieRes.json()
return {
moveData
}
}
}
const fetchMovie = new fetchData
searchInput.addEventListener('keyup', (e) => {
let input = e.target.value;
if (input !== '') {
fetchMovie.getMovies(input)
.then(res => {
let data = res.moveData.Search
console.log(data)
if (!data) {
return false
} else {
let output = ''
data.forEach(movie => {
let poster
if (movie.Poster === "N/A") {
poster = `https://upload.wikimedia.org/wikipedia/commons/a/ac/No_image_available.svg`
} else {
poster = movie.Poster
}
output += `
<div class="col-md-3 movie-card">
<div class="card">
<img class="card-img-top" src="${poster}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">${movie.Title}</h5>
<p class="card-text">${movie.Year}</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>`
});
document.getElementById('container').innerHTML = output;
}
})
.catch(err => console.log(err))
}
e.preventDefault();
})
If you see the log screenshot you first get and undefined
logged. 如果您看到日志屏幕截图,则首先获取并且
undefined
日志。 That is most likely because your fetch happens for each key press, and if you search the API for a single character ( which is what you sent with the first keyup
) you get back no results and thus the forEach
fails. 这很可能是因为您的抓取的每一个按键,如果你搜索API的单个字符( 这是与第一个发送的内容
keyup
)你回来没有结果,因此forEach
失败。
Either check if data has a value before doing the forEach
or don't even send a fetch if the search string is a single character. 在执行
forEach
之前检查数据是否具有值,或者如果搜索字符串是单个字符,甚至不发送获取。
let data = res.moveData.Search
let output = ''
if (!data) return; //early break if not results where returned.
or change if (input !== '') {
to 或将
if (input !== '') {
更改为
if (input.trim().length > 1) { // only do the fetch if more than one characters where entered
although you might still get no results even if you sent more than one characters so the 1st approach is safer. 尽管即使您发送了多个字符,您仍然可能无法获得任何结果,所以第一种方法更安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.