Node.js 从另一个模块访问方法

标签 node.js module

我想从另一个模块访问一个方法,在路由内调用该方法。 使用 module.exports 的这种表示法不起作用,因为在我的控制台中我收到类似 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;

这是我的模块

//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();

最佳答案

主要问题是您导出的不是函数,而是对象。只需导出一个函数:

module.exports = productsController;

另一个问题是你的函数名称不正确,productsController是一个模块,但函数名称应该类似于getProducts:

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

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

并这样使用它:

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

productsController.getProducts();

关于Node.js 从另一个模块访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46033926/

相关文章:

javascript - Promise 异步调用

node.js - Nodejs - 即使在调用 cluster.worker.disconnect() 之后,工作人员仍接受新请求

javascript - 如何在 for 循环中每次强制异步完成,并修改全局变量?

django - 不要在上传模块的帮助下跨 nginx 上传文件

Python导入编译函数

javascript - 服务器端的 CSS?

node.js - Node.js中没有sleep()/wait互斥体,那么如何处理大IO任务呢?

Python - 导入模块的文件名不同?

module - Fortran 中模块使用的模块的变量范围

python - 在不知道存在多少文件的情况下加载 py 文件并在目录的 for 循环中对类执行某些操作?