【问题标题】:How do I get the users input to fetch the api url?如何获取用户输入以获取 api url?
【发布时间】:2021-10-12 17:07:24
【问题描述】:
//OpenWeather Info
const weatherKey = '*********';
const weatherURL = 'https://api.openweathermap.org/data/2.5/weather'

//Page Elements
const input = document.querySelector("#input").value;
const button = document.querySelector('#submit');

//Fetch
const getWeather = async () => {
    try {
        const apiURL = weatherURL+ "?&q=" + input + "&APPID=" + weatherKey;
        console.log(apiURL);
        const response = await fetch(apiURL);
        if (response.ok) {
            const jsonResponse = await response.json();
            console.log(jsonResponse);
            return jsonResponse;
        } else {
            console.log("request failed!");
        }
    } catch (error) {
        console.log(error);
    }
**}**

const renderWeather = (data) => {
    document.querySelector("#weather-degrees").innerHTML = data.main.temp;
}

const executeSearch = () => {
    getWeather().then(data => renderWeather(data));
}

button.addEventListener('click', executeSearch());

当我在文本框中键入时,我无法获取输入的值,并且它不会获取 apiURL。在我输入任何东西之前,控制台就给了我这个。有什么帮助吗? console logs

【问题讨论】:

  • 您必须在调用 fetch 函数之前读取输入值!
  • 您应该小心在线发布 API 密钥,即使您使用的是免费层。

标签: javascript api input fetch-api weather-api


【解决方案1】:

您的input 已预先设置一次。相反,请执行以下操作:

const input = document.querySelector("#input");
// ...
const apiURL = weatherURL+ "?&q=" + input.value + "&APPID=" + weatherKey;
// or using a template literal
const apiURL = `${weatherURL}?&q=${input.value}&APPID=${weatherKey}`;

请注意,您还应该URL encode 输入。

由于input 现在只设置了一次,所以它被设置为一个空字符串。您可以直接访问 API url,即 https://api.openweathermap.org/data/2.5/weather?APPID=82510feaa0c1d3a300a7a754ff134404&q= 并注意它不起作用。如果您将 q= 替换为适当的值,例如q=London,它会正常工作的。

请注意,如果您将无效城市传递给 API,API 也会返回 400 错误(但带有不同的错误消息)。从响应正文中读取错误并正确向用户显示有关无效输入的错误。

【讨论】:

  • 所以我做了你所说的使用模板文字并在 apiURL 中有 input.value 但它仍然给我同样的错误。即使我重新加载它,它仍在尝试在开始时获取。当我在框中输入并单击提交时,也仍然没有收到值。
  • 您是否也将您的const input 更新为不立即阅读.value
  • 是的,我把它换成了你所说的const input = document.querySelector("#input");
  • 哦,我没注意到你也在做button.addEventListener('click', executeSearch());。您基本上是在调用executeSearch() 并说“每当单击按钮时,调用结果”(这不是executeSearch 本身)。你应该改用button.addEventListener('click', executeSearch);
  • 好的,但是现在当我输入一些内容并且什么也不提交时,注销并更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
相关资源
最近更新 更多