【发布时间】:2017-12-29 14:55:39
【问题描述】:
我刚刚开始研究 Fetch API,但在实际使用它时遇到了一些麻烦。作为新手,我的第一个假设是我做错了。
我的第一次尝试是使用带有 Random User 的无密钥 API,效果非常好:
fetch("https://randomuser.me/api/").then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error))
然后,我继续使用 Wunderground Weather 的键控 API,但效果并不好:
fetch("http://api.wunderground.com/api/{API-KEY}/conditions/q/CA/San_Francisco.json").then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error))
在你问之前,我用实际的 API 密钥更改了 URL 字符串中的“{API-KEY}”。但由于某种原因,此 API 调用没有返回任何内容。
API URL 直接从 Wunderground API 文档here 复制/粘贴,如果粘贴到 Chrome 的地址栏中,则成功返回 JSON。
Here 是我正在使用的 codepen.io(无 API-KEY)。
【问题讨论】:
-
可以先测试一下url是否有效?
-
你需要做一个jsonp请求。我不知道 fetch-api 但你应该找到办法。编辑:我刚刚找到它:github.com/camsong/fetch-jsonp 这可能会有所帮助。
-
尝试使用
https://作为 wunderground 网址。 -
@CodyG。成功!将其写为答案,以便我可以将其标记为已解决
-
很高兴它为你工作:)
标签: javascript fetch-api