0

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

directory structure for app

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

error cannot get /

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?

1 Answer 1

1

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');

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.