openweathermap api недопустимая ошибка ключа API [error401]

Я столкнулся с проблемой, связанной с API openweathermap, вызов API отлично работает в браузере, но при использовании его в проекте я получаю ошибку 401, которая упоминается здесь следующим образом: введите здесь описание изображения

у меня нет ни одной из перечисленных проблем

также вот ссылка: http://api.openweathermap.org/data/2.5/weather?zip=10001,us&appid=####

отлично работает в браузере

введите здесь описание изображения

и вот мой app.js:

/* Global Variables */
let baseURL = 'http://api.openweathermap.org/data/2.5/weather?zip=';
let apiKey = ',us&appid=####';



// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();

document.getElementById('generate').addEventListener('click', performAction);

function performAction(e){
  const temperature =  document.getElementById('zip').value;
  const userResponse = document.getElementById('feelings').value;
  console.log(baseURL+temperature+apiKey)
  const getTemp = async (baseURL,temperature,apiKey)=>{
      
      const res = await fetch(baseURL+temperature+apiKey)
    try {

    const data=await res.json();
    return data;
    
    }  catch(error) {
    console.log("error", error);
    // appropriately handle the error
     }
  }
   getTemp(baseURL+temperature+apiKey).then( res =>{ console.log(res);
   
    postData('/add', {temperature: temperature, date: newDate, userResponse: userResponse});
    updateUI('/all');})

когда я console.log() URL-адрес, он работает отлично, но в запросе на получение появляется ошибка: введите здесь описание изображения


person mai mohamed    schedule 15.02.2021    source источник
comment
Скажи мне, что ты не поделился своим закрытым ключом.   -  person emix    schedule 16.02.2021
comment
не уверен, что вы имеете в виду, но если лимит превышен, мы получаем еще одну ошибку   -  person mai mohamed    schedule 16.02.2021
comment
@emix мы получаем ошибку 429   -  person mai mohamed    schedule 16.02.2021
comment
хорошо.. в основном то, что он говорит.. API-ключ, который тебе дали, это не то, что ты должен здесь размещать.. Я ПРЕДЛАГАЮ ВАМ ИЗМЕНИТЬ ЕГО, потому что не у всех такие сердца, как у нас   -  person The Bomb Squad    schedule 16.02.2021


Ответы (1)


getTemp является проблемой
первым аргументом, переданным getTemp, является полный URL-адрес (однако функция объединяет 3 аргумента для URL-адреса выборки)
2 из этих значений, следовательно, будут неопределенными, и выборка закончится как (baseURL+temperature+apiKey)+undefined+undefined вместо baseURL+temperature+apiKey

Решение заключается в том, что при вызове getTemp используйте запятые, чтобы они заполняли соответствующие места аргументов в функции.

/* Global Variables */
let baseURL = 'http://api.openweathermap.org/data/2.5/weather?zip=';
let apiKey = ',us&appid=####';



// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();

document.getElementById('generate').addEventListener('click', performAction);

function performAction(e){
  const temperature =  document.getElementById('zip').value;
  const userResponse = document.getElementById('feelings').value;
  console.log(baseURL+temperature+apiKey)
  const getTemp = async (baseURL,temperature,apiKey)=>{
      
      const res = await fetch(baseURL+temperature+apiKey)
    try {

    const data=await res.json();
    return data;
    
    }  catch(error) {
    console.log("error", error);
    // appropriately handle the error
     }
  }
   getTemp(baseURL,temperature,apiKey).then( res =>{ console.log(res);
   
    postData('/add', {temperature: temperature, date: newDate, userResponse: userResponse});
    updateUI('/all');})
person The Bomb Squad    schedule 15.02.2021
comment
Я видел undefined+undefined и не мог понять причину, теперь это работает! Большое спасибо! - person mai mohamed; 16.02.2021
comment
@TheBombSquad, пожалуйста, удалите ключ API. - person Seth B; 16.02.2021
comment
Я не задавал вопрос @TheBombSquad - person Seth B; 16.02.2021
comment
@TheBombSquad Не думаю, что это так очевидно - person mai mohamed; 16.02.2021