Reputation: 679
I'm building my first node/express app and am following a tut, erroring at step 2 at this link.
I've was able to route data to the template through the app.get render function. In the next step I attempted to move the routes to index.js in the routes directory, and this is where I am getting an error.
Directory Structure
hellotest.js
var express = require('express');
var app = express();
var routes = express.Router('./routes/index');
app.set('view engine','ejs');
var server = app.listen (2000, function(){ console.log('Waiting for you on port 2000'); });
app.use('/', routes);
index.js
var express = require('express');
var app = express();
var routes = express.Router('./routes/index');
app.get ('/', function(req, res){ res.render('default',{title: 'Home', body: 'Datatest'}); });
app.get ('/about-us', function(req, res){ res.send('<h1>Lucius Websystems</h1>Amsterdam, The Netherlands'); });
app.get ('/about/:name?', function(req, res){ var name = req.params.name; res.send('<h1>' +name +'</h1>About text'); });
Browser Error
There are no CLI errors.
I have carefully gone through the tutorial several times and I think there is a step missing (or implied) when decoupling the routing.
Can someone please help me understand why I am getting the Cannot Get / error and how I can properly route the output?
Upvotes: 0
Views: 251
Reputation: 1302
You're very close! The issue is that you're defining your app
in two different places.
Instead, your index.js
should export the router to the server you instantiate in hellotest.js
.
Index.js should look like this:
var express = require('express');
var routes = express.Router();
routes.get('/', function(req, res){ res.render('default',{title: 'Home', body: 'Datatest'}); });
routes.get('/about-us', function(req, res){ res.send('<h1>Lucius Websystems</h1>Amsterdam, The Netherlands'); });
routes.get('/about/:name?', function(req, res){ var name = req.params.name; res.send('<h1>' +name +'</h1>About text'); });
module.exports = routes;
And hellotest.js
should have this line at the top:
var routes = require('./routes/index');
Upvotes: 1