Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
Nish Avatar asked Feb 14 '23 00:02

Nish


2 Answers

Try upgrading to Express 4.x. You are probably running a 3.x flavor.

like image 100
user3624564 Avatar answered Feb 15 '23 16:02

user3624564


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.

app.js

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)
app.use(app.router);

// 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...

views/index.jade

doctype 5
html
  head
    meta(charset='utf-8')
    title #{title}
    meta(name='viewport', content='width=device-width, initial-scale=1.0')
  body
    div
      h1 Gotcha! Title is "#{title}"

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

$ node app.js

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

like image 30
matthias Avatar answered Feb 15 '23 17:02

matthias