how do i fix routes to find views inside subfolders in node.js
I've been dealing with what I think is the same problem and figured out how to fix it. So in case someone else comes across this problem I'm posting my solution.
So here is what I had that was causing 404's and 500's
app.js
var routes = require('./routes/index');var admin = require('./routes/admin');app.use('/', routes);app.use('/admin', admin);
and here was my routes/index.js
//append routesvar express = require('express');var router = express.Router();router.get('/', function(req, res) { res.render('index', {title: 'Express'});});module.exports = router;
and my routes/admin.js:
var express = require('express');var router = express.Router();router.get('/admin', function(req, res) { res.render('admin/index', {title: 'Express'});});module.exports = router;
by defining the second /admin inside the router.get() function I think I was effectively telling node to look for the html in my views folder under the following path views/admin/admin/index.ejs. So to fix that all I had to do was remove either the /admin from the router.get() or the /admin from the app.use() So my working code now looks like this:
app.js
var routes = require('./routes/index');var admin = require('./routes/admin');app.use('/', routes);app.use('/admin', admin); //I left the /admin here and instead removed the one in routes/admin.js
and here was my routes/index.js
//append routesvar express = require('express');var router = express.Router();router.get('/', function(req, res) { res.render('index', {title: 'Express'});});module.exports = router;
and my routes/admin.js:
var express = require('express');var router = express.Router();router.get('/', function(req, res) { //NOTICE THE CHANGE HERE res.render('admin/index', {title: 'Express'});});module.exports = router;
So making that change made it so I could have sub folders in my views folder.
Simple Answer for sub-folders inside the views folder (mine is called frontend)
click here the picture to see the folder structure
file app.jsapp.set('views', [path.join(__dirname, 'frontend'), path.join(__dirname, 'frontend/locked'), path.join(__dirname, 'frontend/template'), path.join(__dirname, 'frontend/public')]);app.set('view engine', 'pug')
I'd check out TJ's video on Modular apps on his vimeo
the best part about this work flow is your code becomes really flexible and it's alot easier to stay DRY
.
Additionally I would do something like this with my app.set("views")
var path = require("path");app.set('views', path.join(__dirname, 'views'));// you can then extend this to the example for routes
Another alternative would be something like in your app.js
file:
var express require("express")var app = express()var routes = require("./path/to/routes")(app)
and then routes would look like:
routes = function (app) { app.get("/route", middleWareifYou.gotIt, route.handler || function (req, res) { res.send("some msg"); });};module.exports = routes
Cheers, I hope this helps!