openweathermap api无效api键错误[error401]

openweathermap api invalid api key error [error401]

我在处理 openweathermap api 时遇到问题,api 调用在浏览器中运行良好,但在项目中使用它时出现错误 401,在此处引用如下:

其中列出的问题有 none 个

这里还有 link: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 它完美运行,但错误出现在 get 请求中:

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');})