Home > Blockchain >  Axios get request format for third party api
Axios get request format for third party api

Time:10-21

I'm currently working on a weather app and am using Axios to execute a get request to a third-party weather API. I'm able to retrieve the data required when I execute the API request on Postman However when I execute this request using Axios I'm getting a 400 bad request error. I've gone through the Axios docs to see if there was a problem in my formatting but I found no differences in their documentation and my code. I've been working on this for a couple of hours now and I'm stumped do you guys see anything wrong with my code that could be causing this error.

This is my code

app.get("/weatherquery/:zip", (req, res) => {
  axios({
    url: "api.openweathermap.org/data/2.5/weather?zip=08060&appid=[CHANGE_FOR_YOUR_APPID]",
  })
    .then((result) => res.send(result))
    .catch((error) => {
      console.log(error);
      res.send(error.message);
    });
});

And this is the error

400
{ connection: 'close' }
{
  transitional: {
    silentJSONParsing: true,
    forcedJSONParsing: true,
    clarifyTimeoutError: false
  },
  adapter: [Function: httpAdapter],
  transformRequest: [ [Function: transformRequest] ],
  transformResponse: [ [Function: transformResponse] ],
  timeout: 0,
  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',
  maxContentLength: -1,
  maxBodyLength: -1,
  validateStatus: [Function: validateStatus],
  headers: {
    Accept: 'application/json, text/plain, */*',
    'User-Agent': 'axios/0.23.0'
  },
  url: 'api.openweathermap.org/data/2.5/weather?zip=08060&appid=73faabe2b55b90dc0d0c89c4899b2a94',
  method: 'get',
  data: undefined
}

CodePudding user response:

Check https:// in url:

var axios = require('axios');

var config = {
  method: 'get',
  url: 'https://api.openweathermap.org/data/2.5/weather?zip=08060&appid=[CHANGE_FOR_YOUR_APPID]',
  headers: { }
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

CodePudding user response:

Whenever an API works in Postman, but not in a webpage, it's likely because of CORS issues. As a security precaution, browsers prevent "cross-site" requests from being made ... eg. requests from yourdomain.com to openweathermap.org.

If openweathermap.org offers CORS support somehow (or JSONP, and older solution) you can still access it. Otherwise you'll need a server of some sort that can serve as a "proxy" (ie. you make a request to your server, at the same domain, and it makes the request to the weather API).

  • Related