0

my application nodejs + express must make requests to another server to build his answers. This request will be used a lot. I would like to put it in a module. I am using the requestjs module. I can build my query and get the right result in the console. But I can not incorporate this code into a module that I could call. There is a lot of example on handling incoming requests but few on outgoing requests. How should I build this module. I know how to do simple modules but not this one. This code does not work. Thanks for your help

var request = require("request") ;

request ("http://example.com", function(error, response, body) {
  myInformation = JSON.parse (body) ;

  mytoken = myInformation.token
  console.log(mytoken);
});


exports.myTest = function () {

return myToken ;
};
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Sven Feb 11 '18 at 23:07

3 Answers3

0

Not sure but I think you need something like this

    module.exports = function() {
        var request = require("request") ;
        return {
           requestBuilder: function(url) {
             let token;
             request (url, function(error, response, body) {
               myInformation = JSON.parse (body) ;
               token = myInformation.token
             });
             return token;
           }
        }
    }


// Use this module as
const token = require('<request module file name>')(url); 
sanket
  • 664
  • 6
  • 16
0

your module can look like this

let request = require("request");

exports.handler = callback => {
  request("http://example.com", function(error, response, body) {
  //call the callback with anything you want
  callback(response);
 });
};

then you need to require your anywhere you want

const { handler } = require('path to your module')

handler(param => {
  console.log(param)
  // do things with the params you sent from your module
})
-1

In this way, doesn't it work? please type your answer and it doesn't, what is the error it shows, please??

var exports = module.exports = {};

let promise = new Promise((resolve, reject) => {

var request = require("request");

    request ("http://example.com", function(error, response, body) {
      myInformation = JSON.parse (body) ;

      mytoken = myInformation.token

      resolve(mytoken);
      console.log(mytoken);
   });

});

exports.getRequestObj = promise;

Later, after you import the function, you'd do...

//With this way, you can recover your value
exportFunction.getRequestObj.then((res) => {
  console.log(res)
})
Kenry Sanchez
  • 1,703
  • 2
  • 18
  • 24