TransWikia.com

Making a API request from inside of a Nodejs application

Stack Overflow Asked by kylebotha on December 9, 2021

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);

One Answer

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 => { ... });

Answered by Nir Alfasi on December 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP