简体   繁体   English

当 API 调用不是以“https://”开头时,为什么 axios 库无法发出请求?

[英]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.因此,我使用 API 来获取有关特定城市当前天气的数据。 The call ( according to the API provider's documentation ) is as follows:调用(根据 API 提供商的文档)如下:

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.控制台显示请求是对一个地址发出的,该地址前面附加了http://localhost:3000/ ,这就是它失败的原因。 When I modify the API call to:当我将 API 调用修改为:

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 将是一个相对 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/',

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Axios API调用不接受参数 - Axios api call doesn't accept parameters 如何使用 Axios 向 API 发出 https 请求? - How can I make a https request to Stripe API with Axios? 该图表未显示我使用 Axios 调用 API 的数据 - The chart doesn't display the data from my call to the API with Axios 嵌套循环中的 Axios API 调用未返回预期结果 - Axios API call in nested loops doesn't return expected results 为什么不“等待”等待 axios 请求完成? - Why doesn't 'await' wait for axios request completes? 当第一次在 React 中使用 Axios 没有错误时进行第二次 api 调用 - Make second api call when there is no error on the first using Axios in React 为什么在进行 axios api 调用时使用 promise? - Why use a promise when making an axios api call? 为什么当我用 Axios 设置数据时它不起作用 - Why when I'm setting Data with Axios it doesn't work Axios 库无法响应 post 请求,尝试使用 curl 和 postman 工作 - Axios library failing to respond for post request, trying with curl and postman works 尝试使用 fetch 而不是 axios 发出 POST 请求,但 fetch 请求的响应返回错误,而 axios 没有 - Trying to use fetch instead of axios to make a POST request, but the response from the fetch request returns an error, whereas axios doesn't
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM