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;
Related
I have been trying to test out express and express handlebars. I have read and tried a few demos. They all basically the same but I cannot get any of them to work. The error I keep getting is -
app.engine('handlebars', exphbs());
^
TypeError: exphbs is not a function
here is my code below:
const express = require("express");
const exphbs = require("express-handlebars");
const app = express();
const port = 8000;
//Handelbars Middleware
app.engine("handlebars", exphbs());
app.set("view engine", "handlebars");
// Index Route
app.get("/", function (req, res) {
res.render("home");
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
I made a short video to further explain - https://www.awesomescreenshot.com/video/6352907?key=df18cdbdf4ed12b85d2c92458ad9a2de
I thought const exphbs = require('express-handlebars'); was declared a function
Thanks
exphbs is not function u can try this code..
const express = require('express');
const exphbs = require('express-handlebars');
// const { engine } = require('express-handlebars');
const app = express();
const port = 8000;
//Handelbars Middleware
//app.engine('handlebars', engine());
app.engine('handlebars', exphbs.engine());
app.set('view engine', 'handlebars');
// Index Route
app.get('/', function (req, res) {
res.render('home');
});
app.listen(port, () =>{
console.log(`Server started on port ${port}`);
});
I think You should use example as reference from express-handlebars. To use this code you need add to your pacakge.json file this line "type": "module",(ES6 import) Good Luck!
import express from 'express';
import { engine } from 'express-handlebars';
const app = express();
app.engine('handlebars', engine());
app.set('view engine', 'handlebars');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('home');
});
app.listen(8000);
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 created a style format with the layout.hbs and notice that all of the pages are not sharing the same consistency in style. I have noticed that I did not declare an app. engine within the app.js. Next, I implemented the app.engine code to set the default layout that is implemented within the layout.hbs
app.engine('hbs', hbs ({extname: 'hbs',defaultLayout: 'layout'}));
An error occurred stating that the layout.hbs cannot be located. I implemented the code again as I noticed I did not direct the folders directories to the layout .hbs. So I implemented the code to
app.engine('hbs', hbs ({extname: 'hbs',defaultLayout: 'layout', layoutsDir:__dirname + '/app_server/views'}));
And the error has disappeared and the default layout structure that has been set to layout.hbs is only showing on the local server index and not the same throughout all of the controllers. I am not too sure what else I am missing
controller and routes code
var express = require('express');
var exphbs = require('express-handlebars');
var router = express.Router();
var ctrlCaribbeanIslands = require('../controllers/CaribbeanIslands')
/* GET home page. */
router.get('/', ctrlCaribbeanIslands.login);
router.get('/blog/add',ctrlCaribbeanIslands.addPost);
router.get('/chat/add',ctrlCaribbeanIslands.addChat);
router.get('/review/add',ctrlCaribbeanIslands.addReview);
router.get('/traceYourTravel', ctrlCaribbeanIslands.tracetravel);
**module.exports = router;**
//controller
module.exports.login = function (req, res) {
res.render('index', { title: 'login'});
};
module.exports.addPost = function(req, res){
res.render('index', { title: 'Add Post' });
};
module.exports.addChat = function(req, res){
res.render('index', { title: 'Add Chat' });
};
module.exports.addReview = function(req, res){
res.render('index', { title: 'Add Review' });
};
module.exports.tracetravel = function(req, res){
res.render('index', { title: 'Trace travel' });
};
app.js
var createError = require('http-errors');
var express = require('express');
var handlebars = require('hbs');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var hbs = require ('express-handlebars');
var indexRouter = require('./app_server/routes/index');
var usersRouter = require('./app_server/routes/users');
var app = express();
app.engine('hbs', hbs ({extname: 'hbs',defaultLayout: 'layout', layoutsDir:__dirname + '/app_server/views'}));
app.set('views', path.join(__dirname, 'app_server','views'));
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
#Zrushb Sorry, my bad, it's with app.set, not use. The code should look like this:
const express = require("express"),
hbs = require("hbs"),
mongoose = require("mongoose")
bodyParser = require("body-[arser")
var app = express()
//In ** your database if you need any
mongoose.connect("mongodb:localhost:27017/**")
app.set("view engine", "hbs")
//To get or post
app.set("view engine", "hbs") //Engine HBS
app.set("views", __dirname +"/views") //Folder views (templates)
app.use(express.static("public")) //Public is static (to get .js, images and .css)
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets'))); //Css folder specified (NOT WORKING)
app.use(bodyParser.urlencoded({extended: false})) //Post Body Parser
app.use(bodyParser.json()) //Parser for JSON files
app.use(cookieParser())
hbs.registerPartials(__dirname+ "views/partials")
app.get("/" //etc)
app.post(//etc)
I think express no longer contains handlebars in it, I'd reccomend to download HBS with npm and then require it var hbs = require('hbs')
Then set the view engine to hbs like this -> app.use("view engine", "hbs")
Try that instead of requiring it from express-handlebars, it has worked for me so far.
app.engine('hbs', hbs({
extname: 'hbs',
defaultLayout: 'layout',
layoutsDir:__dirname + '/app_server/views'
}));
change hbs to hbs.engine like this:
app.engine('hbs', hbs.engine({
extname: 'hbs',
defaultLayout: 'layout',
layoutsDir:__dirname + '/app_server/views'
}));
// view engine setup
(01)app.engine('hbs',hbs({extname:'hbs',defaultLayout:'layout',layoutDir:__dirname+'/views/layouts/'}));
(02) app.set('views', path.join(__dirname, 'views'));
(03) app.set('view engine', 'hbs');
change (01) line like this (hbs to hbs.engine):
app.engine('hbs',hbs.engine({extname:'hbs',defaultLayout:'layout',layoutDir:__dirname+'/views/layouts/'}));
EJS Error: Failed to lookup view "admin_landing2" in views directory "/Users/aryanarora/Desktop/asn3/views".
while trying make a call to localhost/8080/yolo
I am getting the same error even if I switch to hbs. (i have installed both the packages)
var express = require("express");
var app = express();
var port = process.env.PORT || 8080;
var path = require('path');
var bodyParser = require('body-parser')
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var fs = require('fs');
// const hbs = require('hbs');
// hbs.registerPartials(__dirname + './views');
// app.set('view engine','hbs');
// Require static assets from public folder
app.use(express.static(path.join(__dirname, 'public')));
// Set 'views' directory for any views
// being rendered res.render()
app.set('views', path.join(__dirname, 'views'));
// Set view engine as EJS
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
var users = [];
//app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', function(req,res,next){
console.log(req.method, 'request:', req.url);
next();
});
app.locals.yolo = require('./Data/courses.json');
//Request i am trying to get//
app.get('/yolo',function(req,res){
//res.sendFile(path.join(__dirname + '/admin_landing2.hbs'));
res.render('admin_landing2', {var1 : "pehla" , var2 : "dusra"});
});
app.get('/login', function(req,res){
res.sendFile(path.join(__dirname + '/admin_login.html'));
var filepath = './admin_login.html';
console.log(filepath);
});
The problem is that you're setting the views directory to the wrong location.
Do
app.set('views', __dirname)
instead of
app.set('views', path.join(__dirname, 'views'))
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);