Search code examples
javascriptgetfetch-api

I get a 404 error when making a Fetch Get Request


I am trying to get some weather info from a weather api. When I load this fetch code in Chrome's console I get a 404 error.

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();

It also shows this, "http://127.0.0.1:5500/" before the url I'm trying to fetch. What could be causing this to be added and how do I get this fetch request to run properly? I would love any assistance anyone can provide.


Solution

  • The url that you use is considered as a relative url (so the browser prepends it with your site's current location). To make it absolute url, you could either use

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

    or

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

    the last one is to use the same protocol as your site runs on.

    Learn more: Absolute URLs vs relative URLs