0

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.

3
  • 2
    Get 404 error from what? The two pieces of code would operate identically so you must have some other code that is causing a behavior difference. Commented Oct 7, 2015 at 4:54
  • 1
    Are you sure? There is no logical reason for that. Commented Oct 7, 2015 at 4:55
  • Not sure why this post is off-topic. Just trying to learn something here. Please see my update for more detail. Commented Oct 7, 2015 at 5:58

1 Answer 1

1

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
      });
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Calling my function outside the route worked with my previous methodology of wrapping my data.js within module.exports = {} So, I still don't understand why the function will need to be called inside the route in this case?
I don't know how this worked before as it's incorrect. You should first define all your routes and call actions inside them, otherwise it's not guaranteed that your route will be defined inside a callback

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.