I keep getting "app.engine('handlebars', handlebars()); type error 'handlebars' is not a function? Is there anything wrong in my code?
const express = require('express');
const nodemailer = require("nodemailer");
const paths = require('path');
const handlebars = require('express-handlebars')
const app = express();
require("dotenv").config();
//View engine setup
app.set("view engine", 'handlebars');
app.engine('handlebars', handlebars());
//Static Folder
app.use('/public', express.static(path.join(__dirname, 'public')))
//Body Parser MiddleWars;
app.use(express.urlencoded({extended: false}));
app.use(express.json())
const port = 3001;
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
According to the examples express-handlebars provided, you must import the engine function from the module:
(Using Imports)
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(3000);
So, instead of calling handlebars directly, you should be calling handlebars.engine.
In total:
const express = require('express');
const nodemailer = require("nodemailer");
const paths = require('path');
const handlebars = require('express-handlebars')
const app = express();
require("dotenv").config();
//View engine setup
app.set("view engine", 'handlebars');
app.engine('handlebars', handlebars.engine());
//Static Folder
app.use('/public', express.static(path.join(__dirname, 'public')))
//Body Parser MiddleWars;
app.use(express.urlencoded({extended: false}));
app.use(express.json())
const port = 3001;
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
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);
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 want to get my news.ejs page to render when i click its link, but i get a error called "Cannot GET /news.ejs"
const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000
express()
.use(express.static(path.join(__dirname, 'public')))
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req, res) => res.render('pages/index'))
.get('/news', (req, res) => res.render('pages/news'))
.listen(PORT, () => console.log(`Listening on ${ PORT }`))
I have this code and working fine
const express = require('express');
const app = express()
const path = require('path')
const ejs = require('ejs');
app.use(express.static(path.join(__dirname, 'public')))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', ejs)
app.get('/', (req, res) => res.render('privacypolicy.ejs'))
app.get('/news', (req, res) => res.render('rulesnregulations.ejs'))
//app.use('/', indexRouter)
const PORT = 5000;
app.listen(PORT, () => console.log('it started on 5000'))
privacypolicy.ejs & rulesnregulations.ejs these two files are under views folder
Make sure you are linking to /news and not /news.ejs. If you want /news.ejs to be accessible, you will have to change the path that you are registering.
I've been trying to do a route in Express. For example one /about route, but it doesn't work.
var express = require('express');
var app = express();
var router = express.Router();
var moment = require('moment');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/', function (req, res) {
//some action
});
app.get('/time', function (req, res) {
//...
});
app.get('/about', function (req, res) {
res.send('about');
});
Currently after calling url/about I'm getting Cannot GET /about as a return and after some research I've got no idea how to resolve this issue. They even describe it that way in the official express docs.
Thank you in advance.
You have something like this in your code? :
app.listen(SERVER_PORT, function () {
console.log("Server successfully started on port:" + SERVER_PORT); });
We should have something like this:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
const app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/about', routes.about);
and also in the views folder: about.jade
I got a very similar problem with this post Learning Node - Express Public folder not working
I added to my server.js
app.use("public",express.static(__dirname + '/public'));
But when I do
http://localhost:8081/public/css/styles.css
http://localhost:8081/styles.css
Neither works. I got "Cannot GET /public/css/styles.css" and "Cannot GET /styles.css" respectively.
Here is my server.js
var express = require('express')
, cors = require('cors')
, app = express()
, mongoose = require('mongoose')
, models = require('./models')
, bodyParser = require('body-parser')
, controllers = require('./controllers')
, port = 8081//process.env.PORT || 3000
// Config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use("public",express.static(__dirname + '/public'));
app.use('/', controllers);
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/db', function (err) {
if (err) throw err;
console.log("mongoose connected")
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("RESTful Web Services listening at http://%s:%s", host, port)
})
})
Here is the index.js in the controller folder
var express = require('express')
, router = express.Router()
, users = require('./api/users.js')
router.use('/api/user', users);
router.get('/', function (req, res) {
res.render('index.html')
})
//router.use(express.static('public'));
//router.use(express.static('views'));
router.get('/views/demo', function (req, res) {
res.sendFile('/views/demo.html')
})
module.exports = router
Actually, if I run
http://localhost:8081/views/demo.hmtl
I would again get "Failed to load resource: the server responded with a status of 404 (Not Found)"
What did I miss?
I added the following to the server.js and it worked.
app.use('/views', express.static(path.resolve(__dirname, 'views')));
app.use('/public', express.static(path.resolve(__dirname, 'public')));