首页 > 解决方案 > 在 Codesandbox 中获取问题

问题描述

我正在代码沙箱中编写我的代码,并且非常简单地尝试获取天气 API。我已经在代码沙箱中完成了许多 API 调用,它一直都很好,除了这个。

我在控制台中运行它,它也可以很好地返回数据。我真的无法理解是什么原因造成的?如果有人可以看一看并提供帮助,那将非常感激。这是代码:

import React, { useState, useEffect } from "react";

const WeekContainer = () => {
  const [data, setData] = useState([]);

  async function getData() {
    const weatherURL = `http://api.openweathermap.org/data/2.5/forecast?zip=11102&units=imperial&APPID=dcadf332823cddfb979926a1414274e8`;
    const result = await fetch(weatherURL);
    const a = await result.json();
    console.log(a)
    setData(a)
  }

  useEffect(() => {
    getData();
  }, []);

  return <div>weekcontainer</div>;
};

export default WeekContainer;

谢谢你的时间

标签: javascriptreactjsapifetch

解决方案


您的代码给出以下错误 -

The page at 'https://codesandbox.io/' was loaded over HTTPS, but requested an insecure resource 'http://api.openweathermap.org/data/2.5/forecast?zip=11102&units=imperial&APPID=dcadf332823cddfb979926a1414274e8'. This request has been blocked; the content must be served over HTTPS.

这是因为我们无法从 HTTPS 页面访问 HTTP 内容。检查这个 - HTTP Ajax Request via HTTPS Page

您正在尝试从在 HTTPS 上运行并通过 http 调用 api.openweathermap.org 的代码沙箱中获取数据。将 API 请求更改为 https://api.openweathermap.org/data/2.5/forecast?zip=11102&units=imperial&APPID=dcadf332823cddfb979926a1414274e8,您应该能够获取数据。

这是相同的代码框 - https://codesandbox.io/s/trusting-hopper-k5s52


推荐阅读