NodeJS:myFunction()不是函数

时间:2019-07-05 13:32:00

标签: javascript node.js api

我想用可以查询的API制作一个小型的简单Web服务器。 所以我有一个包含以下内容的server.js文件:

var demandeController = require('./api/controller/DemandeController')
var http = require('http')
var express = require('express')
var app = express();

var myRouter = express.Router();

var server = http.createServer();

myRouter.route('/demandes').get((request,response)=>{
var demandes = demandeController.getAllDemandes();
response.json(demandes);
})
app.use(myRouter);
app.listen('8080')

我也有我的模块'DemandeController',其中包含以下内容:

var sql = require('../../node_modules/mssql');
///my secret config
}

module.exports = function getAllDemandes(){
   new sql.ConnectionPool(sqlConfig).connect().then(pool=>{
   return pool.query('SELECT * FROM DEMANDES')
   }).then(result=>{
   return JSON.stringify(result);
})
}

问题是我无法将“ DemandeController”模块导入到server.js文件中。

这是错误消息:

  

TypeError:demandeController.getAllDemandes不是函数       在myRouter.route.get(C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ server.js:11:37)       在Layer.handle上[作为handle_request](C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ node_modules \ express \ lib \ router \ layer.js:95:5)       在下一个(C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ node_modules \ express \ lib \ router \ route.js:137:13)       在Route.dispatch(C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ node_modules \ express \ lib \ router \ route.js:112:3)       在Layer.handle上[作为handle_request](C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ node_modules \ express \ lib \ router \ layer.js:95:5)       在C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ node_modules \ express \ lib \ router \ index.js:281:22       在Function.process_params(C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ node_modules \ express \ lib \ router \ index.js:335:12)       在下一个(C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ node_modules \ express \ lib \ router \ index.js:275:10)       在Function.handle(C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ node_modules \ express \ lib \ router \ index.js:174:3)       在路由器上(C:_AureliaJS \ HotlineFront&Back \ HotlineAPI \ node_modules \ express \ lib \ router \ index.js:47:12)

谢谢您的帮助

2 个答案:

答案 0 :(得分:1)

尝试将您的getAllDemandes()函数放入变量中,并使用module.exports导出变量而不是整个函数

答案 1 :(得分:0)

执行以下操作:

// ./api/controller/DemandeController
module.exports = function() { new sql... }
---
// server.js
const getAllDemandes = require('./api/controller/DemandeController')
// usage: getAllDemandes()

或者那个:

// ./api/controller/DemandeController
module.exports = { getAllDemandes() { new sql... } }
---
// server.js
const DemandeController = require('./api/controller/DemandeController')
// usage: DemandeController.getAllDemandes()