首页 > 解决方案 > 获取请求有一个错误,即 api 实际工作时 url 错误

问题描述

我正在尝试向此 api 发出客户端获取请求:'api.openweathermap.org/data/2.5/weather?zip=' 这里我们需要传递 zip+apiKey 来获得响应: 在此处输入图像描述

我在浏览器中执行此操作,并且成功获得响应: 在此处输入图像描述

在应用程序中尝试执行此操作,但我在“获取请求”中收到错误,即 url 或获取路由错误:

    /* Global Variables */
let baseURL = 'api.openweathermap.org/data/2.5/weather?zip=';
let apiKey = '####';
let appID='&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;
  const getTemp = async (baseURL, temperature, appID,apikey)=>{
      
      const res = await fetch(baseURL+temperature+appID+apikey)
    try {

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

https://codesandbox.io/s/romantic-leaf-0bvpd?file=/src/index.html

标签: javascriptnode.js

解决方案


在这里,您缺少一个“http”协议,因为浏览器会自动添加它。在您的代码中进行以下更改:

let baseURL = 'http://api.openweathermap.org/data/2.5/weather?zip=';
let apiKey = '####';
let appID='&appid='

推荐阅读