Seong Lee
Seong Lee

Reputation: 10580

Exporting module in node.js

I have the following my custom module that successfully exports.

module.exports = function(callback) {

    var request = require("request")
    var url = "http://sheetsu.com/apis/94dc0db4"

    request({
        url: url,
        json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {

            callback(body)

        }
    })

Now if I try to change the way to export this as the following, I get 404 error.

var data = function(callback) {

    var request = require("request")
    var url = "http://sheetsu.com/apis/94dc0db4"

    request({
        url: url,
        json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {

            callback(body)

        }
    })

}

module.exports = data;

What am I doing wrong?

UPDATE

This is the route index.js that renders the received data.

var data = require('../lib/data.js');

data(function(data) {
    router.get('/', function(req, res, next) {
      res.render('index', { 
        title: 'Express', 
        data: data
      });
    });
});

And the error is at at /Users/xxxxx/Dev/Project/app.js:32:13

I haven't changed any other codes except how I changed the export part.

Upvotes: 0

Views: 65

Answers (1)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12334

You should call your function inside the route, not vice a verca:

router.get('/', function(req, res, next) {
  data(function(d) {
      res.render('index', { 
         title: 'Express', 
         data: data
      });
  });
});

Upvotes: 1

Related Questions