Json API在不安全但不安全的环境下工作

Json API在不安全但不安全的环境下工作,json,ajax,api,https,Json,Ajax,Api,Https,所以我正在经历一个Freecodecamp挑战,这似乎是一件很平常的事情 正在从不安全的主机openweathermap.org请求Json 在我的域名http://上,我现在可以让它工作,但在https://上,它不会工作(也可以是代码笔) 我找到了一些变通办法,但没有一个奏效 任何帮助都会很好 由于浏览器安全策略,您无法通过Ajax请求在安全页面(HTTPS)中加载不安全资源(HTTP) 有一个解决方法:在后端创建一个转发层。这些步骤将是: 当您想从http://ip-api.com/js

所以我正在经历一个Freecodecamp挑战,这似乎是一件很平常的事情

正在从不安全的主机openweathermap.org请求Json

在我的域名http://上,我现在可以让它工作,但在https://上,它不会工作(也可以是代码笔)

我找到了一些变通办法,但没有一个奏效

任何帮助都会很好


由于浏览器安全策略,您无法通过Ajax请求在安全页面(HTTPS)中加载不安全资源(HTTP)

有一个解决方法:在后端创建一个转发层。这些步骤将是:

  • 当您想从
    http://ip-api.com/json
    http://api.openweathermap.org
    ,通过HTTPS将Ajax请求发送到您自己的后端API
  • 在后端,接受前面的HTTPS请求,解析参数,并将真正的HTTP请求发送到
    ipapi.com
    api.openweathermap.org
    。检索数据后,将其返回浏览器
  • 在浏览器中,获取数据并进行相应的操作
  • 在codepen中,由于页面是通过HTTP加载的,所以Ajax代码运行良好。可以在调试窗口中观察请求/响应

    function weather() {
    
      // Get Location
      $.getJSON('http://ip-api.com/json', function (response) {
        var city = response.city;
        var country = response.country;
        displayWeather(city, country);
      });
    
      // Make API URL
      function displayWeather(city, country) {
        var weatherAPI = "http://api.openweathermap.org/data/2.5/weather?q=";
        var API_Key = "&APPID=1f3e30098d59daa0ee84d36dca533728";
        var full_API_Link = weatherAPI + city + units + API_Key;  
    
        $.getJSON(full_API_Link, function (response) {
    
          // Interpret data 
          var temp_c = Math.round(response.main.temp);
          var description = response.weather[0].description;
          var icon = response.weather[0].icon;
    
          //Switch Icons and send to DOM
          replace(icon, city, country, temp_c, endUnit, description);
        });
      }
     }