简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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