node.js - adding a new route to node express -
i'm trying add new route in express app keep getting error when trying start server. error
c:\development\node\express_app\node_modules\express\lib\router\index.js:252 throw new error(msg); ^ error: .get() requires callback functions got [object undefined]
here files, i'm new node let me know if left out important file
routes/furniture.js
exports.furniture = function(req, res){ res.render('furniture', { title: '4\267pli' }); };
routes/index.js
/* * home page. */ exports.index = function(req, res){ res.render('index', { title: '4\267pli' }); };
views/furniture.ejs
<!doctype html> <html> <head> <title>4·pli -- architecture</title> <link rel='stylesheet' href='/stylesheets/style.css'/> <link href='http://fonts.googleapis.com/css?family=didact+gothic' rel='stylesheet' type='text/css'> </head> <body> <div class="wrapper"> <h1 class="logo"><%= title %></h1> </div> </body> </html>
app.js
/** * module dependencies. */ var express = require('express') , routes = require('./routes') , user = require('./routes/user') , furniture = require('./routes/furniture') , http = require('http') , path = require('path'); var app = express(); // environments app.set('port', process.env.port || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyparser()); app.use(express.methodoverride()); app.use(app.router); app.use(require('stylus').middleware(__dirname + '/public')); app.use(express.static(path.join(__dirname, 'public'))); // development if ('development' == app.get('env')) { app.use(express.errorhandler()); } app.get('/', routes.index); app.get('/users', user.list); app.get('/furniture', routes.furniture); http.createserver(app).listen(app.get('port'), function(){ console.log('express server listening on port ' + app.get('port')); });
the trouble is:
routes = require('./routes'), user = require('./routes/user'), furniture = require('./routes/furniture'),
these 3 setting routes folders, not specific file, express index.js ( not found, --> error)
inside these folders, should put index.js your:
exports.xxxx = function(req, res){ res.render('xx', { foo: foo}); };
then, project folder structure should like:
routes/ ├── index.js │ ├── user/ │ └── index.js (with exports.user inside) │ └── fourniture/ └── index.js (with exports.furniture inside)
you can add multiple export functions route these:
app.js
// folder called routes index.js file inside routes = require('./routes') . . . app.get('/', routes.main_function); app.get('/sec_route', routes.sec_function); app.post('/other_route', routes.other_function);
/routes/index.js
exports.main_function = function(req, res){ res.render('template1', { foo: foo }); }; exports.sec_function = function(req, res){ res.render('template2', { bar: bar }); }; exports.other_function = function(req, res){ res.render('template1', { baz: baz }); };
Comments
Post a Comment