当我使用变量作为参数时,我的API调用会引发错误,但当我将位置硬编码到API调用中时,却不会引发错误

问题描述

我只是通过使用Openweather.org中的Openweatherapi构建一个简单的Web应用程序来练习API调用和请求。它仅允许您键入城市名称,然后使用按钮提交。获取数据,并返回城市天气的描述。

这是HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <Meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Weather App</title>
    <link rel="stylesheet" href="/css/main.css">
</head>
<body>
    <input type="text" id="cityName">
    <br>
    <button id="citySubmit">Submit city to get weather</button>
   <div id="weatherResponse"></div>
<script src="js/main.js"></script>
</body>
</html>

这是Javascript:

const button = document.getElementById('citySubmit');
const citySearch = document.getElementById('cityName');



const getJSON = async (api) => {
    try {
      const response = await fetch(api);
      if(!response.ok) // check if response worked (no 404 errors etc...)
        throw new Error(response.statusText);
  
      const data = await response.json(); // get JSON from the response
      return data; // returns a promise,which resolves to this data value
    } catch(error) {
      return error;
    }
}

  /*
  //Call funciton and make http request:

  console.log("Fetching data...");
  getJSON(apiCall).then(data => {
    console.log(data);
  }).catch(error => {
    console.error(error);
  });*/

  
  console.log("Fetching data...");//Just to see if it's working.
  getJSON(apiCall).then(data => {
    console.log(data);
  }).catch(error => {
    console.error(error);
  });


  button.addEventListener("click",function(){
//As you can see,Tampa is hard-coded into the API call
    const apiSearch = 'http://api.openweathermap.org/data/2.5/weather?q=tampa&appid={API Key}';
    console.log("Fetching data...");
    getJSON(apiSearch).then(data => {
        
      const cityName = data.name;
      const country = data.sys.country;
      const description = data.weather[0].description;
      //Weather reponse div
       document.getElementById('weatherResponse').append(`The weather in ${cityName},${country} is ${description}.`);
    })/*.catch(error =s> {
      console.error(error);
    });*/
  })

如您所见,坦帕被硬编码到API调用中(省略了键),因此当按下按钮时,它将仅返回坦帕的天气。如果请求是通过这种方式完成的,那么它将起作用。

以下是通话示例的文档:

api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}

当我尝试通过这样编写请求时,使用变量作为参数,将提交到输入字段的城市输入http://api.openweathermap.org/data/2.5/weather?q='+ citySearch +'&appid={API key} ,则会引发404错误

只要将城市硬编码到请求中,API调用就肯定有效。我不确定自己在做什么错。我也使用了示例中给出的括号,但这可能是错误的。我是否在API调用中使用了错误的变量?我很困惑。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)