How to use external routes.js, so I donโ€™t need to define my routes in app.js?

I would like to make a simple link in express. I put in index.jade

a(href='/test', title='View test page') Test 

created in / routes test.js

 /* * GET test page. */ exports.test = function(req, res){ res.render('test', { title: 'Genious test' }); }; 

and 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 an error

 Cannot GET /test 
+4
source share
4 answers

Instead of creating routes / test.js add this value to routes / index.js

 exports.test = function(req, res){ res.render('test', { title: 'Test' }); }; 

Then app.get ('/ test', routes.test); will work as expected.

+3
source

Ok In your app.js application, add the following lines and your problems will be resolved.

 var test = require('./routes/test.js') app.get('/test', test.test); 

This will definitely let your application run and the link is active.

+4
source

This worked for me:

Adding

 exports.newpage = function(req, res){ res.render('newpage'); }; 

in / routes / index.js. Then adding

 app.get('/newpage', routes.newpage); 

under

 app.get('/', routes.index); 

at the bottom of server.js (or app.js).

+1
source

A month after the fact, I am going to answer it differently. You just wanted it to work, and you have a solution for it to work. But what if you really want the other routes.js handle more of your routes? Fear not a node can handle it!

Assuming this structure,

 - app.js - routes/ - index.js - foo.js 

And let's say you need the syntax in app.js

 app.get('/test', routes.foo.test); 

To do this in routes.js add,

 var foo = exports.foo = require('./foo'); 

Then in app.js you will have,

 var routes = require('./routes'); 

This will work, it will let you say in app.js ,

 app.get('/test', routes.foo.test); 

This will give you one more level to organize your routes. I usually like to keep all 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); 
+1
source

All Articles