1

I would to access to a method from another module calling that method inside a route. with this notation of module.exports does't work beacause in my console I get an error like getProducts is not a function

const express = require('express');
const router = express.Router();
const path = require('path');
const productsController = require('../controller/productsController')

const productModel = require('../models/productModel');

// send html file
router.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, '../public/esercitazione-AJAX.html'));
  });
  //to  /getProducts call a method from productsController
  router.get('/getProducts', function (req, res){

  productsController.productsController()
});

module.exports = router;

this is my module

//productsController.js
const productModel = require('../models/productModel');

var productsController = function() {
  console.log('productsController')

  var getProducts = function(req,res,callback) {
    var callback = function(result) {

      res.send(result);
    }
    productModel.getProducts(req, res, callback);
  }
}

module.exports = new  productsController();
alexmac
  • 19,087
  • 7
  • 58
  • 69

1 Answers1

0

The main problem is that you export not a function, but an object. Just export a function:

module.exports = productsController;

Another problem, is that your function has incorrect name, productsController is a module, but function name should be something like getProducts:

exports.getProducts = function() {
  console.log('getProducts ')

  var getProducts = function(req,res,callback) {
    ...

And use it so:

const productsController = require('../controller/productsController');

productsController.getProducts();
alexmac
  • 19,087
  • 7
  • 58
  • 69
  • if I use this notation I get this error TypeError: productsController.getProducts is not a function, I need to export an object and access to a method productsController, this is my goal – Andrea Lunetta Sep 04 '17 at 09:50
  • my mistake sorry, Now I've copied the right code, but this kind of exports is equals to module.exports = new module(); – Andrea Lunetta Sep 04 '17 at 10:20
  • What do you mean? `exports.getProducts` adds a new field to a module object. – alexmac Sep 04 '17 at 10:23
  • I used exports.getProducts, with this notation I ' am exporting all module or just the method getProducts?, – Andrea Lunetta Sep 04 '17 at 10:34
  • You don't understand the conception of CommonJs module, read this question [https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it](https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it) to understand it. – alexmac Sep 04 '17 at 10:36