【发布时间】:2022-02-10 05:13:13
【问题描述】:
我是 Javascript 新手,请多多包涵。我正在尝试拼凑一个网站,我可以去该网站查看我当前在 Spotify 上播放的歌曲。它应该每 1000 毫秒通过 fetch 方法向 Spotify API 发出 GET 请求,并在屏幕上更新 SongNameElement 而无需用户刷新。
我使用了this code,我在网上找到了通过可公开访问的 JSON 文件完成自我更新 div。
我还使用this code 来提供请求标头(令牌等)。
可以在here 找到示例 JSON 数据。我需要this的值
Spotify API 返回一个 JSON 文件。到目前为止,我已经设法在 Python 中实现它,因此对 API 的身份验证不是问题。我正在运行一个烧瓶 Python Web 服务器,它返回 JavaScript 和 HTML(参见下面的代码),但是每当它向 API 发出请求时,promise 都会被标记为待处理,但我不确定它为什么没有完成。以下是我的代码:
import spotipy.util as util
from bs4 import BeautifulSoup
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return """
<div id="SongName">Song Name</div>
<div id="ArtistName">Artist Name</div>
<script>
function updateDataOnScreen() {
const SongNameElement = document.getElementById("SongName")
FetchResponse = fetch("https://api.spotify.com/v1/me/player/currently-playing", {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer (my token goes here, but has been redacted)'
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
})
.then(response => response.json())
.then(json => SongNameElement.innerHTML = FetchResponse)
.catch(error => console.error(error));
console.log(FetchResponse)
}
document.addEventListener("DOMContentLoaded", function(event) {
setInterval(updateDataOnScreen, 1000) // interval value in milliseconds
})
</script>
"""
if __name__ == '__main__':
app.run(debug=True)
开发者工具不断显示this。
注意我已经从标题中编辑了我的令牌,所以如果你自己运行它,你需要用你的 Sptify 令牌替换它,你可以得到here。
【问题讨论】:
-
您在创建分配给它的承诺后立即记录
FetchResponse(并且您创建一个 new 承诺并每 1000 毫秒记录一次)。为什么不会它总是记录为待处理? -
我怀疑您的 真正 问题(因为这很像 XY 问题)是您将
FetchResponse分配给innerHTML而不是json。 (虽然response.json()返回的解析值是从JSON解析的JS数据结构,而不是JSON本身。所以当你将它强制转换为字符串时,它会变成[object Object]) -
那么我应该在哪里/应该改变什么来完成承诺,以便我可以获取数据?
-
使用
then()获取数据(并处理data而不是promise)而不是在promise链之外记录。
标签: javascript html json flask spotify