简体   繁体   English

未捕获(承诺)TypeError:无法读取未定义的属性“ forEach”

[英]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.

相关问题 Angular 7 - 错误错误:未捕获(承诺):类型错误:无法读取未定义的属性“forEach” - Angular 7 - ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined 未捕获的类型错误:无法读取未定义的属性“forEach”//检测未定义 - Uncaught TypeError: Cannot read property 'forEach' of undefined// detect undefined 未捕获(承诺中):TypeError:无法读取未定义的属性“userSubject”类型错误:无法读取未定义的属性“userSubject” - Uncaught (in promise): TypeError: Cannot read property 'userSubject' of undefined TypeError: Cannot read property 'userSubject' of undefined barba.js未被捕获的TypeError:无法读取未定义的属性“ Promise” - barba.js Uncaught TypeError: Cannot read property 'Promise' of undefined 未捕获(承诺):类型错误:无法读取 ionic 2 应用程序中未定义的属性“应用” - Uncaught (in promise): TypeError: Cannot read property 'apply' of undefined in ionic 2 app React Redux - Uncaught(in promise)TypeError:无法读取未定义的属性&#39;props&#39; - React Redux - Uncaught (in promise) TypeError: Cannot read property 'props' of undefined 错误 - 未捕获(承诺)类型错误:无法读取未定义的属性“数据” - Error - Uncaught (in promise) TypeError: Cannot read property 'data' of undefined Axios:未捕获(承诺)TypeError:无法读取未定义的属性“协议” - Axios: Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined 未捕获(在promise中)TypeError:无法读取promiseKey.then上未定义的属性“ length” - Uncaught (in promise) TypeError: Cannot read property 'length' of undefined at promiseKey.then 未捕获(承诺)TypeError:无法读取未定义的属性“ renderMenu” - Uncaught (in promise) TypeError: Cannot read property 'renderMenu' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM