我如何在P5js库上使用API ?



我一直在p5js库上工作,我正试图使用API来访问我的项目的天气数据,但编辑器一直抛出错误,我不知道为什么下面是我的代码:

function setup() {
createCanvas(400,400); 
let url = 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=e7402cc176aacd446829a856f2723b57&units=metric'
loadJSON(url,gotData)
}
function gotData(data){
print(data);  
}
function draw(){
}

有人能帮我指出我的代码有什么问题吗?

你应该发布你得到的错误。(因为你已经使用了p5.js编辑器,你也可以分享一个链接,这样更容易让其他人复制你的问题)

我刚刚在p5 web编辑器中尝试了您的代码,我在浏览器的JS控制台中得到此错误:

p5.js:84555 Mixed Content: The page at 'https://editor.p5js.org/' was loaded over HTTPS, but requested an insecure resource 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=e7402cc176aacd446829a856f2723b57&units=metric'. This request has been blocked; the content must be served over HTTPS.

有时错误可能是隐晦的,但在这种情况下,它非常直接:

  • p5.js从HTTPS域(https://editor.p5js.org)加载
  • 通过HTTP(不安全)(http://api.openweathermap.org/...etc.)访问天气API
  • 理想情况下,你应该通过HTTPS加载(天气API支持HTTPS)。

这使得解决方案就像添加一个's'一样简单:)(访问Weather API时从http://https://)

function setup() {
createCanvas(400,400); 
let url = 'https://api.openweathermap.org/data/2.5/weather?q=London&appid=e7402cc176aacd446829a856f2723b57&units=metric'
loadJSON(url,gotData)
}
function gotData(data){
print(data);  
}
function draw(){
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

最新更新