I have an error with directories and paths.
Look, this is my server config file:
const path = require("path");
const exphbs = require("express-handlebars");
const morgan = require("morgan");
const multer = require("multer");
const express = require("express");
const erroHandler = require("errorhandler");
const routes = require("../routes/index");
module.exports = app => {
app.set("port", process.env.PORT || 3000);
console.log("0. " + __dirname);
let parent = path.normalize(__dirname + "/src/");
console.log("1. " + parent);
app.set('views', path.join(__dirname, '../views'));
let d = app.get("views");
console.log("2. " + d);
app.engine(
".hbs",
exphbs({
extName: ".hbs",
defaultLayout: "main",
partialsDir: [ path.join(__dirname, '../views') ],
layoutDir: path.join(__dirname, '../views', 'layouts'),
helpers: require("../helpers")
})
);
app.set("view engine", ".hbs");
// middlewares
app.use(morgan("dev"));
app.use(
multer({ dest: path.join(__dirname, "../public/upload/temp") }).single(
"image"
)
);
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
//routes
routes(app);
// static files
app.use("/public", express.static(path.join(__dirname, "../public")));
// errorhandlers
if ("development" === app.get("env")) {
app.use(erroHandler);
}
return app;
};
And I get some error like this:
I know it's not the extension but the route. I will show you my directories:
I am getting this error:
Error: ENOENT: no such file or directory, open 'C:\Users\Diesan
Romero\Desktop\redsocial\views\layouts\main.handlebars'
Your path to your layout is incorrect this is what the error message is telling you
looking at your folder structure \Users\Diesan Romero\Desktop\redsocial\views\layouts\main.handlebars should be this: \Users\Diesan Romero\Desktop\redsocial\src\views\layouts\main.handlebars. You are missing the src directory between your redsocial and views directories.
Just declare views folder like this
app.set('views', path.join(__dirname, '../views'));
And change the app.engine like this
app.engine(
".hbs",
exphbs({
extName: ".hbs",
defaultLayout: "main",
partialsDir: [ path.join(__dirname, '../views') ]
layoutDir: path.join(__dirname, '../views', 'layouts'),
helpers: require("../helpers")
})
);
I produced the same error on my side and then fixed it hopefully 90 percent it will do the trick
Related
i have made the handlebars template config on my index.js file, but when i try to run my code with nodemon he returns me this error. anyone can help?
enter image description here
enter image description here
Problem
You initialization of engine on line 8 is wrong.
Solution
Please change it to app.engine('handlebars', engine());. Check the snippet below.
Implementation
const express = require('express');
const { engine } = require ('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(3000);
Reference
Express-Handlebars
Insert .engine after handlebars, look:
app.engine('handlebars', handlebars.engine({ defaultLayout: 'main' }));
const { engine } = require("express-handlebars");
app.engine(
"hbs",
engine({
extname: "hbs",
defaultLayout: false,
layoutsDir: "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'))
Handlebars template's filename extension
Hi,
my templates files got the extension .handlebars and I want to change it to .hbs
const express = require('express');
const exphbs = require('express-handlebars');
const app = express();
app.engine('handlebars', exphbs({defaultLayout: 'index'}));
app.set('view engine', 'handlebars');
when changing handlebars to hbs and renaming the files, errors appear. The files are not found anymore.
What is missing?
Try setting the following properties
const exphbs = require('express-handlebars');
const handlebars = exphbs.create({
// layoutsDir: path.join(__dirname, 'app/views/layouts'),
// partialsDir: path.join(__dirname, 'app/views/partials'),
defaultLayout: 'index',
extname: 'hbs'
});
app.engine('hbs', handlebars.engine);
app.set('view engine', '.hbs');
Change your code something like this:
`
const express = require('express');
var app = express();
const hbs = require('express-handlebars');
app.set('views', path.join(__dirname, 'views'));
app.engine('hbs', hbs({extname : 'hbs', defaultLayout: 'index', layoutsDir: __dirname+'/views/layouts'}));
app.set('view engine', 'hbs');
Change your file's extentions from
.hanlebars
to
.hbs and put your index.hbs file inside path/to/project/views/layouts and rest of the .hbs file should remain in path/to/project/views/.
My css files are served as html/text instead of as stylesheet. Resulting in the css does not work. Heres the error message:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:3030/css/bootstrap.css".
And here's my server.js
var express = require('express'),
stylus = require('stylus'),
logger = require('morgan'),
bodyParser = require('body-parser'),
path = require('path');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
function compile(str, path){
return stylus(str).set('filename', path);
}
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(stylus.middleware(
{
src: __dirname + '/public',
compile: compile
}
));
app.use(express.static(__dirname + 'public'));
app.get('*', function(req, res){
res.render('index');
});
var port = 3030;
app.listen(port);
console.log('Listening on port ' + port + '...');
Can anyone help me??
Try this- If you are using nodemon change to http-server https://www.npmjs.com/package/http-server
I am trying to properly use i18n with hbs, but haven't had any success.
Here is my server.js code:
var express = require('express');
var server = express();
var hbs = require('hbs');
var i18n = require('i18n');
var cookieParser = require('cookie-parser');
i18n.configure({
locales: ['en', 'fr'],
cookie: 'locale',
directory: __dirname + "/locales"
});
hbs.registerPartials(__dirname + '/views');
server.set('view engine', 'hbs');
server.engine('hbs', hbs.__express);
server.use(cookieParser());
server.use(i18n.init);
hbs.registerHelper('__', function () {
return i18n.__.apply(this, arguments);
});
hbs.registerHelper('__n', function () {
return i18n.__n.apply(this, arguments);
});
server.get('/', function(req, res) {
res.render('index');
});
And my HTML code :
<ul class="nav navbar-nav navbar-right">
<li>{{__ 'HOME'}}</li>
<li>{{__ 'TEAM'}}</li>
<li>{{__ 'SERVICES'}}</li>
<li>{{{__ 'LEL'}}}</li>
</ul>
And one of my Json files :
{
"HOME": "HOME",
"TEAM": "TEAM",
"SERVICES": "SERVICES",
"LEL": "CONTACT"
}
I can't see what I am doing wrong, if someone could help me bit it would be really helpful! Thank you!
Edit : It seems that my helpers are recognized, but i18n is not translating words..
Édit : Ok I changed my template engine and it worked !
I did it like this
const express = require('express');
const path = require('path');
const handlebars = require('handlebars');
const app = express();
const i18n = require('i18n');
// Language
i18n.configure({
locales: ['es', 'en'],
directory: path.join(__dirname, 'locales'),
defaultLocale: 'es',
queryParameter: 'lang',
});
app.engine('.hbs', exphbs({
defaultLayout: 'index',
layoutsDir: path.join(app.get('views'), 'layouts'),
partialsDir: path.join(app.get('views'), 'partials'),
extname: '.hbs',
handlebars: allowInsecurePrototypeAccess(handlebars),
helpers: {
i18n: function(){
return i18n.__.apply(this,arguments);
},
__n: function(){
return i18n.__n.apply(this, arguments);
},
}
}));
app.set('view engine', 'hbs');
app.use(i18n.init);
and in any .hbs file
<h1>{{i18n 'Hello'}}<h1>