提出获取请求时出现404错误

时间:2018-09-27 21:50:38

标签: javascript api get fetch

我正在尝试从天气api获取一些天气信息。当我在Chrome的控制台中加载此提取代码时,出现404错误。

const getWeather = () => {
  return fetch('api.openweathermap.org/data/2.5/weather? 
q=London&appid=' + apiKey)
  .then(response => response.json())
  .then(weather => console.log(JSON.stringify(weather)))
}

getWeather();

它还会在我尝试获取的网址之前显示“ http://127.0.0.1:5500/”。是什么原因导致添加此错误,以及如何获取此提取请求才能正常运行?我希望任何人都能提供任何帮助。

1 个答案:

答案 0 :(得分:0)

您使用的网址被视为相对网址(因此浏览器会在该网址的前面加上您网站的当前位置)。要使其成为绝对网址,您可以使用

'https://api.openweathermap.org/data/2.5/weather?q=London&appid=' + apiKey

'//api.openweathermap.org/data/2.5/weather?q=London&appid=' + apiKey

最后一个是使用与您的网站运行相同的协议。

了解更多:Absolute URLs vs relative URLs