Search code examples
node.jsexpresspugjs

Why can't I call any page created in node express?


I'm using the ExpressJS web framework for NodeJS.

I don't know why to have 404 error messages when creating a new page and call it.

My directory structure:

| my-application
    | src
        | routes
            | index.js
            | single.js
        | views
            | index.pug
            | single.pug
        | ...

Code single.js in routes folder:

var express = require('express');
var router = express.Router();

/* GET single page. */
router.get('/single', function(req, res, next) {
  res.render('single', { title: 'Blog single' });
});

module.exports = router;

Code in app.js:

// ...
var index = require('./src/routes/index');
var single = require('./src/routes/single');

app.use('/', index);
app.use('/single', single);
// ...

Solution

  • This line of code:

    app.use('/single', single);
    

    along with the single router creates a route handler for /single/single, not for just /single. It registers a router to handle all /single routes and then that router itself registers /single creating the handler for /single/single.

    You can either change the router.get() to handle just / instead of /single. or you can change the app.use() to not have a path. You probably want to change the router.