Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics Parameters, Query Strings, and Modularizing Routes Modular Routes

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

'Register' route in Express.js not working

Hi all,

I've successfully modularised the Express app as shown in the video. But there's one route that isn't working properly no matter what I try.

I realise that it's not necessary to have this route to finish the course so I could easily just delete it and move on but I'd love to know what's happening here if possible.

The error is

Error: Can't set headers after they are sent.

So it's quite a common one and I've seen it a lot when developing this app. The res.end() commands in the route don't affect what happens.

app.js
const express = require('express');

//import body-parser middleware
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");

//list data
const names = [
    "Jack Bauer",
    "Jill Green",
    "John Joe",
    "Jonah Whale",
    "Jamaal LH",
    "Joe Fisher"
]


//Express launch function
const app = express();
//set the view engine to use pug for templating
app.set("view engine", "pug");


//use bodyParser and cookieParser middleware - third party.
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

const indexRouter = require("./routes");
const cardsRouter = require("./routes/cards");

app.use(indexRouter);
app.use(cardsRouter);

/*MIDDLEWARE*/

/* app.use((req, res, next) => {
    console.log("Hello");
    next();
 });

 app.use((req, res, next) => {
    console.log(", World");
    next();
 }); */

//404 Middleware!
app.use((res, req, next) => {
    const err = new Error('Page Not Found!');
    err.status = 404;
    next(err);
});

//error handler middleware
app.use((err, req, res, next) => {
    // do something
    //res.status(err.status)   
    res.locals.error = err;
    res.status(err.status);
    res.render('error');
    next();
    res.end();

 });

//Set up the development server listen method - port number
app.listen(3000, function(){
    console.log("server currently running on Heroku");

});
index.js
const express = require("express");
const routes = express.Router();

/*ROUTES*/

//serve the home route
routes.get('/', (req, res) => {

    const name = req.cookies.username;

    //basic response with the send method
    if(name) {        
        res.render('index', {name, page_title: "Flash Card App"});
    } else {
        res.redirect('/hello');
    }
     //res.end();
 });

//serve the register route
routes.get('/register', (req, res) => {

    //basic response with the send method
    res.render('register', {page_title: "Flash Card App: Register of users", names});
    //res.end();

 });

//serve the 4th route which will be a post route 
routes.get('/hello', (req, res) => {

    //store cookie
    const name = req.cookies.username;

    //perform actions based on setting of cookie
    if(name) {
        res.redirect('/');
    } else {
        res.render('hello', { page_title: "Flash Card App: Hello Route"});
    }

    //res.end();

 });

 routes.post('/hello', (req, res) => {

    const name = req.body.username;

    //basic response with the send method,
    res.cookie('username', name);
    res.redirect('/');

    //console.log(req.body);
    //res.end();

 });

 routes.post('/goodbye', (req, res) => {

    //res.clearCookie(req.cookies.username);
    res.clearCookie('username');
    res.redirect('/hello');
 });

 //export index routes to app.js
 module.exports = routes;
cards.js
const express = require("express");
const routes = express.Router();

 //serve the cards route
 routes.get('/cards', (req, res) => {

    //basic response with the send method
     res.render('cards', {page_title: "Flash Card App", prompt: "Who is buried in Grant's tomb?"});
     //res.end();
 });


 //export cards routes to app.js
 module.exports = routes;
Tyler McDonald
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tyler McDonald
Full Stack JavaScript Techdegree Graduate 16,700 Points

Hey Jonathan,

I'm having the exact same issue. I have an array of names within app.js that I was rendering into a /sandbox route, but once I modularized the app by moving the routes into the routes folder, it broke that page. I can't figure out how to "export" the array (if that's what it would be called, although it's just simple js data) to make it accessible from index.js. It would be nice to have it in a completely separate file.

Were you able to figure this one out?

1 Answer

Blake Larson
Blake Larson
13,014 Points
res.render('register', {page_title: "Flash Card App: Register of users", names}); <--- names

I no longer have a sub so I can't see the video, but I'm guessing it's because you can't access the names array from app.js anymore so probably just export the names for index.js. Try that, I think its right but I haven't been using view engines lately so I'm rusty.

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,253 Points

Thanks Blake.

Apologies for the late reply. Been a busy Monday and weekend.

Eventually, I simply copied and pasted the data into the index.js file rather than tried to export it which caused its own problems but I got there in the end. Thanks for your help! :)