Here is my structure like
app.js
routes
index.js
views
partials
index.ejs
This is index.js in routes folder that is rendering the template called index.ejs form views folder
const express = require('express');
const router = express.Router();
const expressLayouts = require('express-ejs-layouts');
const path = require('path');
router.get('/', (req, res) => {
res.render(path.join(__dirname, '../index'));
})
module.exports = router;
Error says Failed to lookup view "layout" in views directory
You have to set the views directory first in app.js:
const express = require("express");
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
router.get('/', (req, res) => {
res.render('index.ejs'));
})
Related
router.get('/dist/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
my app.js routing code
app.set('dist', path.join(__dirname, 'dist'));
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
my folder structure
root/dist/index.html
I cannot open this page on my first page
how can I open this page? Where is my mistake?
thank you for your help
You can use the method set() to redefine express's default settings.
app.set('views', path.join(__dirname, '/dist'));
Working Example
const express = require('express')
const path = require('path')
const app = express()
const port = 3000;
var indexRouter = require('./routes/index');
// Set 'views' directory for any views
// being rendered res.render()
app.set('views', path.join(__dirname, '/dist'));
// Set view engine
app.engine('html', require('hbs').__express);
app.set('view engine', 'html');
app.use('/', indexRouter);
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/dist/', function(req, res, next) {
res.render('index', { title: 'Inside Dist Folder Index' });
});
module.exports = router;
I am getting an error while routing file as Error: file not found
File structure
Controller
--orgaizationController
--blogesController
--pagesController
Views
--organization.ejs
--bloges.ejs
--pages.ejs
--index.ejs
organizationController.js
const express = require('express');
const router = express.Router();
router.get('/',async (req,res) => {
res.render('index');
});
router.get('/addedOrganization', async (req,res) => {
res.render('addedOrganization' , {});
});
server.js
const blogsController = require('./Controllers/campaignController');
const organizationController = require('./Controllers/campaignController');
const pagesController = require('./Controllers/campaignController');
app.use('/', organizationController)
app.use('/', blogsController)
app.use('/', pagesController)
Image
But when I change app.use('/', organizationController) to app.use('/organiztion', organizationController) I get the index page i.e my homepage
Please anyone help?
You need to set this middleware to render views without mentioning the path
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
I am trying to develop an application in NodeJs using express framework. My routing is working when I navigating from home to inner pages. But If I want to navigate from some inner page to homepage then it is not working.
Below is my app.js code.
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
//declare all routers
var home = require(path.join(__dirname, "/routes/index"));
var myaccount = require(path.join(__dirname, "/routes/myaccount"));
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine('html', engines.handlebars);
var defaultViewPath = path.join(__dirname, "/views");
app.set('views', defaultViewPath);
app.set('view engine', 'html');
app.use('/', home);
app.use('/myaccount', myaccount);
Here if I have navigated from home to myaccount - Its working
But if I am navigating from myaacount to home - It reloads the same page.
Can anyone help me to resolve this issue.
To define routing using methods of the Express app object, use app.get() to handle GET requests
var express = require('express')
var app = express()
// When GET request is made to the homepage
app.get('/', function (req, res) {
res.render('home');
});
// When GET request is made to the myaccount
app.get('/myaccount', function (req, res) {
res.render('myaccount');
});
app.get('/myaccount/innerpage', function (req, res) {
res.send('Hello Inner Page');
});
//Page Not Found
app.use(function(req, res){
//render the html page
//res.render('404');
res.sendStatus(404);
});
Hope this could help you
use app.get and app.post Route Methods
app.get('/',function(req,res){
res.render('home');
});
app.get('/myaccount',function(req,res){
res.render('myaccount');
});
Or Create Router File For Home & myAccount
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Home Page')
})
module.exports = router
in Your app.js or index.js file , require route.js
var home = require('./route');
app.use('/', home)
My express version is 4.13.1.
My express dir is that:
app.js
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use('/user',require('./controllers'));
controllers/index.js
var express = require('express');
var router = module.exports = express.Router();
router.use('/signup', require('./signup'));
controllers/signup/index.js
var express = require('express');
var router = module.exports = express.Router();
router.get('/', function(req, res, next) {
res.render('signup', { title: 'Signup' });
});
Then use 'http://localhost:3000/user/signup/' in browser,throw Error:
I'm waiting online,thank you.
You should specify all directories which contain views, for example:
var views = [
path.join(__dirname, 'views'),
path.join(__dirname, 'controllers/signups/views')
];
app.set('views', views);
i am trying to create a route for localhost:port/admin/
and i want to keep the routes.js files and view.js files in matching folders so i wont have too much spaggeti later on
but i keep getting: 500 Error: Failed to lookup view "/admin/manage_subjects"
for trying to create a new route and using same folders few the same
i have the following view folder with express
mainapp(root)
routes(folder)
admin(folder)
index.js(nested inside admin)
index.js(nested inside routes)
views(folder)
admin(folder)
admin_layout.jade(nested inside admin)
manage_subjects.jade(nested inside admin)
index.jade(nested inside views)
layout.jade(nested inside views)
code:
routes/admin/index.js
exports.index = function (req, res) {
res.render('manage_subjects',{title:'Express'});}
views/admin/manage_subjects.jade
extends admin_layout
block content
h1 = title
p Welcome to #{title}
my app.js code
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, admin_routes = require('./routes/admin/')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, repository = new (require('./domain_model/repository'))();
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//fill local subjects
repository.subjects.GetAll(function (err, data) {
if (err) throw err;
app.locals.subjects = data;
});
//append routes
app.get('/', routes.index);
app.get('/admin', admin_routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on http://localhost:' + app.get('port'));
});
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 routes
var 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 routes
var 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.js
app.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!
I had a similar problem and what worked for me was setting the views folder in both the main app file and in the router file too.
So in the main app.js file I had:
app.set('views', viewsFolderPath);
And inside my router.js file I also did the same thing:
app.set('views', viewsFolderPath);