繁体   English   中英

从 Nodejs 应用程序内部发出 API 请求

[英]Making a API request from inside of a Nodejs application

我正在尝试向外部 API 发出请求,以便我可以在我自己的 API 的响应中使用响应数据,但我似乎无法自行获取响应数据以便我可以使用它在我自己的 API 中,我将如何使用 module.exports 从发出外部 API 请求的文件中返回响应数据?

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

您可以从模块中将其导出为 function:

文件: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);
  });
};

从另一个模块(在同一文件夹中):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM