Use ejs instead of pug template in express - javascript

I am just a newbie in node js using node js with express framework. Currently the express framework is using pug template engine. I want to use ejs template. So how to do that. My app.js is looking like this
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var admin = require('./routes/admin');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/admin', admin);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;

first
npm install ejs
and then replace
app.set('view engine', 'pug');
with
app.set('view engine', 'ejs');

Related

File Upload returning "undefined"

So I am using Express File Upload and when I attempt to send a post request to it, it returns the error from the error-handler that is set up, which essentially it couldn't find any files when I console.log(req.files) it returns undefined, which is why the error is being sent back, but I don't know how to fix the problem.
Index.js
router.post('/upload-avatar', async (req, res) => {
try {
console.log(req.files)
if(!req.files) {
res.send({
status: false,
message: 'No file uploaded'
});
} else {
//Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
let avatar = req.files.avatar;
//Use the mv() method to place the file in upload directory (i.e. "uploads")
avatar.mv('./uploads/' + avatar.name);
//send response
res.send({
status: true,
message: 'File is uploaded',
data: {
name: avatar.name,
mimetype: avatar.mimetype,
size: avatar.size
}
});
}
} catch (err) {
res.status(500).send(err);
}
});
App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fileUpload = require('express-fileupload');
const cors = require('cors');
const bodyParser = require('body-parser');
const _ = require('lodash');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
app.use(fileUpload({
createParentPath: true
}));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// 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;
I am using an azure server, and at the moment I am using postman to get it working first!
Thanks In Advance!
Middlewares should be ordered appropriately. Your file upload middleware was placed below your index router. So when a request hits the server Express would run your indexRouter’s handler before the upload middleware and unless your handler calls next(), the file upload middleware would not process your request. And you cannot call next() since it would mean “I’m done with my part, hand this request (req) to the next middleware/handler”.
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fileUpload = require('express-fileupload');
const cors = require('cors');
const bodyParser = require('body-parser');
const _ = require('lodash');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(fileUpload({
createParentPath: true
}));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
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;

Internal server error when using ejs with expressjs

I'm new to nodejs and I'm trying to use ejs to template my website. But when I tried to set the view engine, I keep getting the error code 500 - Internal Server Error. Here is my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var engines = require('consolidate');
var index = require('./routes/index');
var main = require('./routes/main');
var suoimo = require('./routes/suoimo');
var vungtau = require('./routes/vungtau');
var video = require('./routes/video');
var dalat = require('./routes/dalat');
var app = express();
app.use(express.static('./'));
app.use(express.static('./public'));
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.engine('html', engines.mustache);
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', index);
app.use('/video', video);
app.use('/', index);
app.use('/suoimo', suoimo);
app.use('/vungtau', vungtau);
app.use('/main', main);
app.use('/dalat', dalat);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
But if I set the view and view engine like this:
app.set('views', path.join(__dirname, 'views'));
app.engine('html', engines.mustache);
app.set('view engine', 'html');
Everything work fine, anyone know why? Please help
I tested your code and everything works fine. But if I uninstall ejs I get error 500 Internal server error. I think that this is your problem. Try to run npm install ejs and try again with the same configuration, it should work fine now.

Node js not returning proper result?

I have this node js program which should return asked variable in the console but it is returning undefined here is code and the input i have trying to parse :-
router.post('/createorder',function(req,res){
console.log(req.body.ProductName);
// var obj=JSON.parse(req.body);
res.send(req.body);
});
the input :
{
"ProductName":"Wine",
"ProductPrice":"500",
"ProductQuantity":"2",
"ProductCost":"1000",
"SellerId":"2"
}
and here is the main module i'm using
var express= require('express');
var routes=require('./routes/api');
var bodyparser=require('body-parser');
var mysql = require('mysql');
var db=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'nodemysql'
})
//setting up express
var app = express();
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
app.use(routes);
//listen for requests
/*app.get('/',function(req,res){
console.log('get trial method called');
res.send({name:'Atul'});
});*/
app.listen(3000,function(){
console.log('server started on port 3000 ');
});
i want to acess an specific object in order to store in the database?
As soueuls mentioned in the comments, you need to make sure express can parse the body of the request as it doesn't do this by default. Assuming you are using express framework. You could have something like this.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
Now you can read the body.
notice if you console log your req object before you add in the code above, you will not see the body property.
UPDATE
this is what i have in my app.js file
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
In my routes/index.js i have the following
var express = require('express');
var router = express.Router();
router.post('/createorder',function(req,res){
console.log(req.body);
// var obj=JSON.parse(req.body);
res.send(req.body);
});
module.exports = router;
i tested this with postman app and it works.

node js app variable is not defined in coffeescript

I am just going through nodejs, expressjs and coffeescript. My code is,
app.js
require('coffee-script').register();
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var index = require('./routes/index');
//var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', index);
//app.use('/users', users);
require('./apps/authentication/routes')(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
My CoffeeScript Code is.
routes.coffee
routes = (app) ->
app.get "/login", (req , res) ->
res.render "views/login",
title: 'Login'
stylesheet: 'login'
module.export = routes
When i run project, i face following issue.
app.get("/login", function(req, res) {
^
ReferenceError: app is not defined
can anyone tell me why app variable is not defined at whereas i am passing app variable when requiring route?
If i remove white spaces from coffeescript file as mentioned below
routes = (app) ->
app.get "/login", (req , res) ->
res.render "views/login",
title: 'Login'
stylesheet: 'login'
module.export = routes
it return exception require(...) is not a function as mentioned below
require('./apps/authentication/routes')(app);
^
TypeError: require(...) is not a function
Thanks
Finally, I am able to fix this, it was syntax error in coffeescript.
I just changed
module.export
to
module.exports
Thanks,

nodejs separate code include middleware use()

I'm new to nodejs, below is my app.js I installed by express --sessions --css less --hogan app command.
I tried to separate the commented line in app.js move to a new file call route_handler.js.
I'm not sure am I doing correct I only add a require('./route_handler.js'); in app.js and should I have to export in route_handler.js but it is express() ?
How to solve it?
Does require means already execute the code in the file?
app.js
var express = require('express');
var path = require('path');
// var favicon = require('serve-favicon');
// var logger = require('morgan');
// var cookieParser = require('cookie-parser');
// var bodyParser = require('body-parser');
// var routes = require('./routes/index');
// var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// end: view engine setup
require('./route_handler.js');
// // uncomment after placing your favicon in /public
// //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger('dev'));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false }));
// app.use(cookieParser());
// app.use(require('less-middleware')(path.join(__dirname, 'public')));
// app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', routes);
// app.use('/users', users);
// // catch 404 and forward to error handler
// app.use(function(req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
// // error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
route_handler.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// var app = express();
var routes = require('./routes/index');
var users = require('./routes/users');
// uncomment after placing your favicon in /public
//express().use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
express().use(logger('dev'));
express().use(bodyParser.json());
express().use(bodyParser.urlencoded({ extended: false }));
express().use(cookieParser());
express().use(require('less-middleware')(path.join(__dirname, 'public')));
express().use(express.static(path.join(__dirname, 'public')));
express().use('/', routes);
express().use('/users', users);
// catch 404 and forward to error handler
express().use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// expore express() ??
Your problem is that the route_handler.js script creates new express instances in every use call, and non of them are connected to the app created in your app.js.
What you should probably do is something like:
route_handler.js
// !!!NOTE: no express = require !!!
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
function setupRoutes(app)
{
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
...
}
module.exports = setupRoutes;
and app.js
...
require('./route_handler.js')(app);
...

Categories