0

I have a code like this:

const req = require("request");
const apiReq = req("http://example.com/car/items.json", (err, res, body) => {
  if (!err && res.statusCode === 200) {
    return JSON.parse(body);
  }
})

console.log(apiReq)

module.exports.api = apiReq;

If I console log inside apiReq It returns me actual JSON response but I want to export it. Console.log(apiReq) returns me request object. What is wrong with this code?

Miqez
  • 173
  • 1
  • 2
  • 15

2 Answers2

3

In your example, the HTTP request is getting executed when NodeJS reads your file (which you probably don't want it to do because it's a bad habbit).

You can solve this by using a callback.

const req = require("request");
module.exports = function (successCb, errorCb) {
  req("http://example.com/car/items.json", (err, res, body) => {
    if (err) return errorCb(err);
    // You may want to add an additional check for statusCode 200
    // How you handle that depends on your scenario.

    successCb(JSON.parse(body));
  })
}

From another file

const yourReqModule = require('your-req-module')

yourReqModule(function(jsonResponse) {
  handleJsonResponse...
}, function (error) {
   // Handle error
});

By using this technique, the HTTP request wont be executed until you actually run yourReqModule.api().

Edit:

You should always include error handling. I've updated the code with an example implementation of that.

kontrollanten
  • 2,649
  • 19
  • 32
3

You can try exporting a function instead of the request object.

const request = require('request')

module.exports = function makeRequest(cb){
  return new Promise((reject, resolve) => {
    request("http://example.com/car/items.json", (err, response, body) => {
        if(cb){
          if(err)
            return cb(err)
          return cb(null, JSON.parse(body));
        } else {
            if(err)
              return reject(err);
            return resolve(JSON.parse(body));
        }
    })
  })
}

Then, in some other module,

var makeAPIRequest = require('./path/to/module')
makeAPIRequest().then(...).catch(...);
// or via callback
makeAPIRequest((error, body) => {
  if(error){
    // handle error
  } else {
    // handle response
  }
})
riyaz-ali
  • 8,677
  • 2
  • 22
  • 35