【问题标题】:get request has an error that the url is wrong while the api actually works获取请求有一个错误,即 api 实际工作时 url 错误
【发布时间】:2021-05-18 13:59:02
【问题描述】:

我正在尝试向此 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

【问题讨论】:

  • 添加 URL 的协议部分:https://api...
  • 它在那里并给出了同样的错误,所以我删除了它
  • 我注意到“不安全” - 使用 http://api...
  • @RandyCasburn 是一样的
  • 错误是什么?还是坏网址?使用与浏览器图像中显示的完全相同的 URL,看看是否仍然出现错误 - 但请确保包含 URL。

标签: javascript node.js


【解决方案1】:

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

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

【讨论】:

  • 它在那里,我删除了它,因为有同样的错误
  • 您是否检查了您使用日志创建的 URL?
  • 我在浏览器中查看过
  • 不在浏览器中。尝试 console.log(baseURL+temperature+appID+apikey)。是否与实际网址匹配?
  • @MohammadYaserAhmadi 是的,这些步骤对你真的很有帮助'Mai'。另外,如果您还没有添加,请在您的代码正文解析器中包含它。
猜你喜欢
  • 1970-01-01
  • 2015-01-03
  • 2020-12-03
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
相关资源
最近更新 更多