I'd like to do a simple link in express. I put into the index.jade
a(href='/test', title='View test page') Test
created in /routes a test.js
/*
* GET test page.
*/
exports.test = function(req, res){
res.render('test', { title: 'Genious test' });
};
and a simple test.jade in /views
extends layout
block content
h1= title
p Test page
I added in app.js
app.get('/test', routes.test);
If I click on the link I get the error
Cannot GET /test
Ok. In your app.js add the following lines, and your problems will be solved.
var test = require('./routes/test.js')
app.get('/test', test.test);
This will definitely allow for your app to run and the link to be active.
Instead of creating routes/test.js, add this on to routes/index.js
exports.test = function(req, res){
res.render('test', { title: 'Test' });
};
Then app.get('/test', routes.test); will work as expected.
This worked for me:
Adding
exports.newpage = function(req, res){
res.render('newpage');
};
to /routes/index.js. Then adding
app.get('/newpage', routes.newpage);
under
app.get('/', routes.index);
at the bottom of server.js (or app.js).
Months after the fact, I'm going to answer this a different way. You simply wanted it to work and you got a solution for it to work. But, what if you really wanted another routes.js to handle more of your routes? Fear not node can handle this!
Assuming this structure,
- app.js
- routes/
- index.js
- foo.js
And, let's say you want the syntax in your app.js
app.get('/test', routes.foo.test);
For this, in routes.js add,
var foo = exports.foo = require('./foo');
Then in app.js you'll have,
var routes = require('./routes');
This will work, it'll allow you to say in app.js,
app.get('/test', routes.foo.test);
This will give you another level to organize your routes. I usually like to keep all of my routes organized under the routes object, but if you want to import directly into main you can too,
var foo = require('./routes/foo');
app.get('/test', foo.test);