kylebotha
kylebotha

Reputation: 35

Making a API request from inside of a Nodejs application

I'm trying to make a request to an external API so that I can use the response data in the response of my own API, but I can't seem to get the response data on it`s own so that I can use it in my own API, how would I use module.exports to return the response data from the file where I'm making the external API request ?

var axios = require("axios");

var config = {
  method: "get",
  url: "https://some-api",
  headers: {},
};

axios(config)
  .then(function (response) {
     //how can I export response.data from the file
    console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log(error);
  });

console.log(response);

Upvotes: 1

Views: 46

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53525

You can export it a a function from your module:

file: data.js

var axios = require("axios");

var config = {
  method: "get",
  url: "https://some-api",
  headers: {},
};

exports.getData = () => {
  return axios(config).then(function (response) {
    console.log(JSON.stringify(response.data));
    return response.data; // this returns the data
  }).catch(function (error) {
    console.error(error);
  });
};

from another module (in the same folder):

const { getData } = require('./data');
getData().then(data => { ... });

Upvotes: 4

Related Questions