我正在为摄影师构建一个简单的作品集网站。我要显示的集合类型称为宠物图片,其中包含标题和图像字段。我可以使用异步函数调用 API,但是一旦我从 API 获得 JSON 数据,我就无法访问照片的 URL。例如,我可以创建一个标题来显示每个宠物图片的标题,但我不能使用标准对象表示法来访问 JSON 数据中的 URL,然后显示图像。这真的不可能吗?我有点失去理智了。
例如,采用如下所示的 JSON 数据数组:
{
"id": 1,
"Title": "Santa Dog Picture",
"published_at": "2021-03-29T02:45:32.389Z",
"created_at": "2021-03-29T02:45:23.362Z",
"updated_at": "2021-03-29T02:45:32.414Z",
"Photo": {
"id": 3,
"name": "Pets3.jpg",
"alternativeText": "",
"caption": "",
"width": 4000,
"height": 6000,
"formats": {
"thumbnail": {
"name": "thumbnail_Pets3.jpg",
"hash": "thumbnail_Pets3_a4be530d90",
"ext": ".jpg",
"mime": "image/jpeg",
"width": 104,
"height": 156,
"size": 5.74,
"path": null,
"url": "/uploads/thumbnail_Pets3_a4be530d90.jpg"
},
"large": {
"name": "large_Pets3.jpg",
"hash": "large_Pets3_a4be530d90",
"ext": ".jpg",
"mime": "image/jpeg",
"width": 667,
"height": 1000,
"size": 85.36,
"path": null,
"url": "/uploads/large_Pets3_a4be530d90.jpg"
},
"medium": {
"name": "medium_Pets3.jpg",
"hash": "medium_Pets3_a4be530d90",
"ext": ".jpg",
"mime": "image/jpeg",
"width": 500,
"height": 750,
"size": 56.22,
"path": null,
"url": "/uploads/medium_Pets3_a4be530d90.jpg"
},
"small": {
"name": "small_Pets3.jpg",
"hash": "small_Pets3_a4be530d90",
"ext": ".jpg",
"mime": "image/jpeg",
"width": 333,
"height": 500,
"size": 31.39,
"path": null,
"url": "/uploads/small_Pets3_a4be530d90.jpg"
}
},
"hash": "Pets3_a4be530d90",
"ext": ".jpg",
"mime": "image/jpeg",
"size": 2031.2,
"url": "/uploads/Pets3_a4be530d90.jpg",
"previewUrl": null,
"provider": "local",
"provider_metadata": null,
"created_at": "2021-03-29T02:42:56.325Z",
"updated_at": "2021-03-29T02:42:56.464Z"
}
}
这不起作用:
const displayPhoto = async () => {
const response = await fetch('/pet-pictures')
const petPictures = await response.json()
console.log(petPictures)
const container = document.querySelector('#pets')
petPictures.forEach((picture) =>{
const photo = document.createElement('img')
photo.setAttribute('src', picture.Photo.formats.small.url)
container.appendChild(photo)
})
}
displayPhoto()
我得到一个 TypeError: cannot read property 'formats' of undefined。但是,如果我用标题替换照片,并创建一个 h1 并将其文本内容设置为 picture.title,那就可以了。我在这里疯了!如果我遗漏了一些非常明显和令人尴尬的东西,我深表歉意。