Javascript 获取API";无法读取属性';forEach&x27;“未定义”的定义;

Javascript 获取API";无法读取属性';forEach&x27;“未定义”的定义;,javascript,ecmascript-6,xmlhttprequest,fetch,Javascript,Ecmascript 6,Xmlhttprequest,Fetch,我正在尝试使用Pixabay API获取图像。我有一个输入字段,我将获取该值并将其插入url字符串中。我能拉,我能成功地得到回复。当我尝试循环遍历数组并拉入图像时,它说“无法读取未定义的属性'forEach'。我不知道发生了什么事?这是我的密码: const imgForm=document.querySelector(“搜索表单”); imgForm.addEventListener(“提交”,获取图像); 函数获取图像(e){ e、 预防默认值(); const searchTerm=do

我正在尝试使用Pixabay API获取图像。我有一个输入字段,我将获取该值并将其插入url字符串中。我能拉,我能成功地得到回复。当我尝试循环遍历数组并拉入图像时,它说“无法读取未定义的属性'forEach'。我不知道发生了什么事?这是我的密码:

const imgForm=document.querySelector(“搜索表单”);
imgForm.addEventListener(“提交”,获取图像);
函数获取图像(e){
e、 预防默认值();
const searchTerm=document.querySelector(“.search”).value;
取回(`https://pixabay.com/api/?key=8772164-4F816AA8FC1FC304525290454A0&q=${searchTerm}&image\u type=photo&pretty=true`)
.then((response)=>{return response.json();})
。然后((resp=>{
控制台日志(resp);
设hitsArray=resp.data;
展示图像(hitsArray);
}))
.catch(err=>console.log(err));
}
函数showImages(hitsArray){
const results=document.querySelector(“.results”);
控制台日志(结果);
让输出=“”;
hitsArray.forEach((imgData)=>{
输出+=`
`;
});
document.querySelector('.results').innerHTML=output;
}

您正在使用
让hitsArray=resp.data

当它应该是
时,让hitsArray=resp


响应上没有
数据
属性。

响应没有
数据
属性-相反,它有一个
命中
属性和您要查找的数组。另一个问题是传递给
forEach
的函数的参数是迭代的数组元素,而不是

imgData.hits.largeImageURL
只需访问
largeImageURL
属性:

imgData.largeImageURL
const imgForm=document.querySelector(“搜索表单”);
imgForm.addEventListener(“提交”,获取图像);
函数获取图像(e){
e、 预防默认值();
const searchTerm=document.querySelector(“.search”).value;
取回(`https://pixabay.com/api/?key=8772164-4F816AA8FC1FC304525290454A0&q=${searchTerm}&image\u type=photo&pretty=true`)
。然后((响应)=>{
返回response.json();
})
。然后((resp=>{
让hitsArray=相应的命中率;
展示图像(hitsArray);
}))
.catch(err=>console.log('err:'+err));
}
函数showImages(hitsArray){
const results=document.querySelector(“.results”);
让输出=“”;
hitsArray.forEach((imgData)=>{
输出+=`
`;
});
document.querySelector('.results').innerHTML=output;
}

感谢您对我的错误进行了很好的解释。那真的很有帮助!