Search code examples
javascriptnode.jsexpressgetcontrollers

I get an error when I try to import a get request from a controller module to my main app. (Type-error : Cannot read proper 'get' of undefined)


This is my index.js file in my ./home directory:

var express = require('express');
var control = require('./controllers/todoController');
var app = express();

//set up template engine

app.set('view engine', 'ejs');

//static files
app.use(express.static('./public'));

//fire controllers

control();

//listen to port
app.listen(3000);
console.log('You are listening to port 3000');

This is my todoController.js file in my ./home/controllers directory:

module.exports =function(app){
  app.get('/quiz', function(req, res){
  res.render('quiz');
});
};

The error that is shown is:

TypeError : cannot read property 'get' of undefined

Solution

  • Use the router module of expressjs

    const express = require('express');
    const router = express.Router();
    
    /* GET home page. */
    router.get('/', function(req, res, next) {
        var token = req.body.token('token');
        if(!token)
        {
            res.render('error', {
                'message': "You must indicate a Token"
            });
        }
        
    });
    
    module.exports = router;

    Then, just import it on your app.js main file :

    app.use('/', tokenHandler);