Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 279
obiwankenoobi Avatar asked Feb 24 '18 07:02

obiwankenoobi


People also ask

How do you do a GET request with Axios?

A GET request can be made with Axios to “get” data from a server. The HTTP get request is performed by calling axios. get() .

How do I bypass Axios base url?

To change the default base URL for Axios, we can set the baseUrl option when we're calling our axios instance. this. $axios({ url: "items", baseURL: "http://new-url.com" }); to call this.

Does Axios work with HTTP?

Axios works by making HTTP requests with NodeJS and XMLHttpRequests on the browser. If the request was successful, you will receive a response with the data requested. If the request failed, you will get an error. You can also intercept the requests and responses and transform or modify them.

What does an Axios get request return?

It prints the web site's url, server name, and status code. const fetchUrl = (url) => axios. get(url); The axios. get makes an async request and returns a promise.


1 Answers

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', {
like image 171
Patrick Hund Avatar answered Oct 27 '22 13:10

Patrick Hund