ChillAndCode
ChillAndCode

Reputation: 308

NodeJS : myFunction() is not a function

I want to make a small simple web server with an API that I could query. So I have a server.js file that contains this:

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')

I also have my module 'DemandeController' which contains this :

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

The problem is that I can not import my "DemandeController" module into my server.js file.

Here is the error message:

TypeError: demandeController.getAllDemandes is not a function at myRouter.route.get (C:_AureliaJS\HotlineFront&Back\HotlineAPI\server.js:11:37) at Layer.handle [as handle_request] (C:_AureliaJS\HotlineFront&Back\HotlineAPI\node_modules\express\lib\router\layer.js:95:5) at next (C:_AureliaJS\HotlineFront&Back\HotlineAPI\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:_AureliaJS\HotlineFront&Back\HotlineAPI\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:_AureliaJS\HotlineFront&Back\HotlineAPI\node_modules\express\lib\router\layer.js:95:5) at C:_AureliaJS\HotlineFront&Back\HotlineAPI\node_modules\express\lib\router\index.js:281:22 at Function.process_params (C:_AureliaJS\HotlineFront&Back\HotlineAPI\node_modules\express\lib\router\index.js:335:12) at next (C:_AureliaJS\HotlineFront&Back\HotlineAPI\node_modules\express\lib\router\index.js:275:10) at Function.handle (C:_AureliaJS\HotlineFront&Back\HotlineAPI\node_modules\express\lib\router\index.js:174:3) at router (C:_AureliaJS\HotlineFront&Back\HotlineAPI\node_modules\express\lib\router\index.js:47:12)

Thank you for your help

Upvotes: 0

Views: 466

Answers (2)

Nino Filiu
Nino Filiu

Reputation: 18551

Either do this:

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

Or that:

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

Upvotes: 0

Sashfish
Sashfish

Reputation: 36

Try putting your getAllDemandes() function into a variable and export the variable instead of the whole function with module.exports

Upvotes: 1

Related Questions