HTTP get request with Axios gets sent with the local host IP at the beginning of the URL

删除回忆录丶 提交于 2021-02-07 06:20:05

问题


I am trying to sent an HTTP request with Axios, but I get a 404 error. The reason is that the request gets sent with the local host IP at the beginning of the URL, why is this happening?

JS:

function getWeather() {

  axios.get('api.openweathermap.org/data/2.5/weather', {
    params: {
      lat: 30.18,
      lon: 30.87,
      appid: '57d9478bc08bc211f405f45b93b79272'
    }
  })
  .then(function(response) {
    console.log(response);
  })

  .catch(function(error) {
    console.log(error);
  })
};
getWeather();  

ERROR:

http://127.0.0.1:5500/api.openweathermap.org/data/2.5/weather?lat=30.18&lon=30.87&appid=57d9478b#####################3b79272 404 (Not Found)

回答1:


In the URL argument for Axios, you are not specifying the protocol to use for your API request (probably HTTP). Because of that, Axios interprets it as a relative URL path and adds the path of your local server, because it needs a full URL to make the request.

You can easily fix it by adding the http:// prefix:

axios.get('http://api.openweathermap.org/data/2.5/weather', {



回答2:


you can config the axios base url before your request

axios.defaults.baseURL = 'http://api.openweathermap.org';
axios.get('/data/2.5/weather')


来源:https://stackoverflow.com/questions/48960497/http-get-request-with-axios-gets-sent-with-the-local-host-ip-at-the-beginning-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!