node js TypeError: Cannot read property 'get' of undefined using cloud9 IDE

2.5k views Asked by At

I am using a the cloud9 ide and getting an error as described in the title. The file structure looks like this

client/
  views/
   -index.ejs
   routes/
    -index.js
-server.js 

server.js file

var path = require('path');
var async = require('async');
var express = require('express');
var router = express();
var server = http.createServer(router);

router.use(express.static(path.resolve(__dirname, 'client')));


router.set('view engine','ejs');
//app.set('views','app/views');
router.locals.siteTitle = "Meetups";

//router.use(express.static(path.resolve('./public')));
router.use(require('./client/routes/index'));
router.use(require('./client/routes/speaker'));
 server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
  var addr = server.address();
  console.log("Chat server listening at", addr.address + ":" + addr.port);
});

While my index.js inside the routes folder which is receiving the error

TypeError: Cannot read property 'get' of undefined router.get('/',function(req,res){

 var express = require('express');
var router = express.Router();
  router.get('/',function(req,res){
  res.render('index',{
    pageTitle:'Home',
    pageID:'home',
  });
});

module.exports = router;
1

There are 1 answers

0
hisener On

I have copied your code to my c9 ide.

First issue in server.js you need to require http module.

var http = require("http");

And I have deleted this line because you didn't share this file.

router.use(require('./client/routes/speaker'));

It worked. At least, Node didn't throw any error.

Chat server listening at 0.0.0.0:8080

But I have some recommendations for you.

  • First of all, in server.js please rename "router" variable to "app", because it's not a route module.
  • For public folder, do not use client folder, create a folder named "public". Because you have routes, views, etc in client folder.
  • For require expressions, try to make it at the top of the file.
var routes = require('./client/routes');

// some code ...

app.use('/', routes);
  • And import only one file for routes. Import other route files in routes/index.js

  • I prefer createServer just before server.listen

var server = http.createServer(app);
server.listen(...)