Internal server error when using ejs with expressjs - javascript

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.

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;

Use ejs instead of pug template in express

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');

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.

Why router in Express/node.js return 404

I just generated Express app and added custom route (/configuration). But if I try to open http://localhost:3000/configuration, server returns 404 Not Found error. I checked the code and don't understand where is error.
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 index = require('./routes/index');
var config_page = require('./routes/configuration');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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('/configuration', config_page);
// 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;
routes/configuration.js (routes/index.js is similar)
var express = require('express');
var router = express.Router();
/* GET configuration page. */
router.get('/configuration', function(req, res, next) {
res.render('configuration', { title: 'My App | Configuration' });
});
module.exports = router;
This code is the problem
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Also the current Url which is generated by your application is http://localhost:3000/configuration/configuration. If you make a query on this then it will work. Now if you wan to use it with http://localhost:3000/configuration. then you need to remove on path from anywhere. May be you can change in main file like this
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('/',config_page); //-----------> this is the line you need to change
How can it be used for error handling. Remove it and add this code to catch any error in application.
process.on('uncaughtException', function (err) {
// This should not happen
logger.error("Pheew ....! Something unexpected happened. This should be handled more gracefully. I am sorry. The culprit is: ", err);
});

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,

Categories