Nish Nish -4 years ago 155
Javascript Question

Using Route of express node.js but express.Router getting as undefined

My code of router from default routes/index

/* GET home page. */
exports.index = function(req, res){
res.render('user', { title: 'Abcd' });

var express = require('express');

var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });

router.get('/helloworld', function(req, res) {
res.render('helloworld', { title: 'Hello, World!' })

module.exports = router;

getting error as can not call method get of undefined.I am new in node js please anyone help me.

Answer Source

Router is a middleware of express which is registered implicitly with the express object the first time post() or get() is used. You can but don't have to add this explicitly calling use(), which allows you to register various middleware with express and so allows configuring processing and behavior in consideration of precedence.

Correct initialization and usage might look like this:

EDIT: Changed the example to be a "complete" http server.


var http = require('http');
var express = require('express');

// Requiring express exports a function that creates the application. Call it!
var app = express();

// Set port to listen to
app.set('port', process.env.PORT || 3000);

// Set view engine
app.set('view engine', 'jade');

// Tell express to use the router middleware
// Can be omitted if precedence doesn't matter 
// (e.g. for loading static resources)

// Add callback handler for home (/) route
app.get('/', function(req, res) {
  res.render('index', { title: 'Express' });

// Create http server by passing "app" to it:
http.createServer(app).listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));

Now, if you place a minimal view into the default folder for views...


doctype 5
    title #{title}
    meta(name='viewport', content='width=device-width, initial-scale=1.0')
      h1 Gotcha! Title is "#{title}"

... and start your server from the console with...

$ node app.js should have your first node/express/jade powered app up and running!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download