简体   繁体   中英

Why is axios Library failing to make a request when an API call doesn't start with "https://"?

This is not an issue to me anymore, as I solved this problem, but I still want to ask it to better understand what is happening under the hood. So, I use an API to fetch data about current weather in a specific city. The call ( according to the API provider's documentation ) is as follows:

axios.get(`api.openweathermap.org/data/2.5/weather?q=${countryCapital}&appid=%{API_KEY}`)

Such request fails. The console shows that the request was made to an address that has http://localhost:3000/ appended in front of it, which is why it fails. When I modify the API call to:

axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${countryCapital}&appid=%{API_KEY}`)

then everything works as intended. Why is that so?

When you don't specify the scheme, the URL would be a relative URL!

  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `baseURL` will be prepended to `url` unless `url` is absolute.
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM