我正在尝试使用src将图像设置为html元素。该图像是我从Spotify获得链接的Spotify专辑封面(链接看起来像这样:https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828)
这是我的代码:
const getSongData = () => {
currentlyPlaying= localStorage.getItem("currentlyPlaying");
songDuration = localStorage.getItem("songDuration");
currentAlbum = localStorage.getItem("currentAlbum");
currentArtist = localStorage.getItem("currentArtist");
currentAlbumCover = localStorage.getItem("currentAlbumCover");
document.getElementById('currentlyPlaying').innerHTML = currentlyPlaying;
document.getElementById('songDuration').innerHTML = (`${(songDuration/1000)/60}:${(songDuration/1000)%60}`);
document.getElementById('currentAlbum').innerHTML = currentAlbum;
document.getElementById('currentArtist').innerHTML = currentArtist;
document.getElementById('currentAlbumCover').src = currentAlbumCover;
//console.log(currentAlbumCover);
}
因此变量currentAlbumCover
包含链接,但是这不起作用,我收到此错误消息:
有趣的是,如果我这样直接放置链接,它就可以正常工作:
document.getElementById('currentAlbumCover').src = 'https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828';
您收到的错误显示找不到404。
这是因为在所需的链接之前添加了http://localhost:5500
。
您最终将获得http://localhost:5500/https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828
当您只想要https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828
时
[我怀疑localStorage.getItem("currentAlbumCover")
返回的是汇总值,所以也许值得检查一下如何将值保存到localStorage。
尝试在控制台中转储变量,看起来您有一个绝对URL用作相对路径。
如果我的想法是正确的,则将转储:/https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828
所以currentAlbumCover
前面可能有一个'/'。
希望这会有所帮助!