How to add routing to sub folders in express.js?

Viewed 23

I'm trying to break my routes.js file into separate files so it's easier to work with.

Here is my folder structure

routes.js
views/
├─ 1537/
│  ├─ prototype-4/
│  │  ├─ _routes.js
│  │  ├─ report.html

routes.js

const express = require('express')
const router = express.Router()

router.use('/1537/prototype-4', require('./views/1537/prototype-4/_routes'));

module.exports = router

views/1537/prototype-4/_routes.js

const express = require('express')
const router = express.Router()

router.get('/report/:reportId', function (req, res) {
    console.log("Hello world");
    res.render("report");
});

module.exports = router

When I run the following it returns 'hello world' but it can't find the template.

template not found: report.html

Can someone please point me in the right direction?

1 Answers

Just needed to use nodejs' __dirname to resolve the path in views/1537/prototype-4/_routes.js

const express = require('express')
const router = express.Router()

router.get('/report/:reportId', function (req, res) {
    console.log("Hello world");
    res.render(__dirname + "/report");
});

module.exports = router
Related