Reputation: 3859
I keep getting this error message after refactoring my code into separate js files. I have tried numerous different methods based on SO posts but nothing seems to work, I either get this error or the app variable is undefined
in my controller.
I am a complete Node novice so if someone can point me in the right direction I would be very grateful!
Node version: v6.17.0
app.js
const express = require('express');
const app = express();
const controller = require('./plate-controller');
module.exports.app = app;
controller
const plateService = require('./plate-service');
var app = require('./app').app;
var exports = module.exports = {};
exports.controller = function(app) {
app.get('/plates/:plate_id', function (req, res) {
return plateService.getPlateById(req, res);
});
app.get('/plates/search/:plate', function (req, res) {
return plateService.search(req, res);
});
app.get('/plates/current-plates', function (req, res) {
return plateService.getCurrentPlates(req, res);
});
app.get('plates/prefix-plates', function (req, res) {
return plateService.getPrefixPlates(req, res);
});
};
This gives undefined and trying to call like require('..')()
always give the is not a function
error.
When printing out the controller variable to the console it actually doesnt look as I thought it would, a function, rather its a function inside an object so I suppose that is the cause of the require(...) is not a function
.
{ controller: [Function] }
Upvotes: 0
Views: 254
Reputation: 3859
I think I have worked this out now so in case this saves someone else some pain then here is the way I did it, I had followed a tutorial to get this far and I didnt realise that the function would be wrapped in an object when it was returned.
If there is a better way to do this then please let me know.
const controllerExports = require('./plate-controller');
controllerExports.controller(app);
Upvotes: 0
Reputation: 2134
When require
is called, module.exports
is returned. export
is not returned.
instead of using exports.controller
use module.exports.controller
like this:
module.exports.controller = function(app) {
app.get('/plates/:plate_id', function (req, res) {
return plateService.getPlateById(req, res);
});
app.get('/plates/search/:plate', function (req, res) {
return plateService.search(req, res);
});
app.get('/plates/current-plates', function (req, res) {
return plateService.getCurrentPlates(req, res);
});
app.get('plates/prefix-plates', function (req, res) {
return plateService.getPrefixPlates(req, res);
});
};
For more information, you can look at this answer
Upvotes: 1