"no default engine" error when running MEAN application - node.js

Error: Failed to lookup view "error" in views directory "/var/www/html/mean/mean-secure1/views"
at Function.render (/var/www/html/mean/mean-secure1/node_modules/express/lib/application.js:581:17)
at ServerResponse.render (/var/www/html/mean/mean-secure1/node_modules/express/lib/response.js:1008:7)
at /var/www/html/mean/mean-secure1/app.js:50:7
at Layer.handle_error (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:315:13)
at /var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:275:10)
at /var/www/html/mean/mean-secure1/app.js:39:3
at Layer.handle [as handle_request] (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:317:13)
at /var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/var/www/html/mean/mean-secure1/node_modules/serve-static/index.js:121:7)
at SendStream.emit (events.js:182:13)
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/database');
var api = require('./routes/api');
var app = express();
//app.set('view engine', 'pug');
mongoose.Promise = require('bluebird');
mongoose.connect(config.database, { promiseLibrary: require('bluebird') })
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
app.use(passport.initialize());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'false'}));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/books', express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
//app.use(express.static(path.join(_dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// 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;

If you want to use ejs templating as your view engine then you can use below code to set the view engine for your node application
const ejs=require("ejs");
app.set('view engine','ejs');

Related

req.checkBody is not a function with Express-Validator NODEJS

Hi I'm trying doing a login page, after clicking on submit I'm getting this error with express-validator version 5.3.1
req.checkBody is not a function
TypeError: req.checkBody is not a function
at Strategy._verify (C:\Users\aless\Desktop\js_cart-master\config\passport.js:67:7)
at Strategy.authenticate (C:\Users\aless\Desktop\js_cart-master\node_modules\passport-local\lib\strategy.js:90:12)
at attempt (C:\Users\aless\Desktop\js_cart-master\node_modules\passport\lib\middleware\authenticate.js:369:16)
at authenticate (C:\Users\aless\Desktop\js_cart-master\node_modules\passport\lib\middleware\authenticate.js:370:7)
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:275:10)
at C:\Users\aless\Desktop\js_cart-master\routes\user.js:39:3
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:317:13)
at C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:335:12)
In my app.js I have required express-validator with const validator = require('express-validator');//#5.3.1
and used it with app.use(validator());
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const passport =require('passport');
const flash = require('connect-flash');
const bcrypt = require('bcrypt');
const validator = require('express-validator');//#5.3.1
const session = require('express-session');
const MongoStore = require('connect-mongo');
const env = require('dotenv').config()
const app = express();
mongoose.connect(process.env.URI,{ useNewUrlParser: true });
require('./config/passport');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({
secret: "key per i cookie",
saveUninitialized: false,
resave: false,
store: MongoStore.create({
mongoUrl: process.env.URI,
autoRemove: 'disabled'
}),
cookie: { maxAge:30000,secure:false }
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//verify if authenticated
app.use((req, res, next)=>{
res.locals.login =req.isAuthenticated();
//access sessions through templates
res.locals.session = req.session;
next();
});
//routes
app.use('/', require('./routes/index'));
app.use('/user', require('./routes/user'));
// 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;
Using this express-validator version I got this error when submit, using last express-validator version I get same error in console.
Why I'm getting this error??
The reason is the way you are requiring it.
const { body, validationResult } = require('express-validator');
In your code you can make these changes and try:
const { validationResult } = require('express-validator');//#5.3.1
.
.
.
app.use(validationResult());
Note: check this link for more information.

Express router 404 Not Found

I used express-generator and the following are app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var app = express();
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
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;
And when access to http://localhost:5000/api/ got Error:
Not Found
404
NotFoundError: Not Found
at D:\_projects\booking-system\api\app.js:28:8
at Layer.handle [as handle_request] (D:\_projects\booking-system\api\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\_projects\booking-system\api\node_modules\express\lib\router\index.js:317:13)
at D:_projects\booking-system\api\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:335:12)
at next (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:275:10)
at D:_projects\booking-system\api\node_modules\express\lib\router\index.js:635:15
at next (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:260:14)
at Function.handle (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:174:3)
at router (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:47:12)
Following is routes/index:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'API' });
});
module.exports = router;
Thank you very much for your helps !
The issue is that you define a GET / route in your routes/index.js file and then register it as app.use('/', indexRouter) in your app.js.
So you either change your routes/index.js file to it looks like this:
var express = require('express');
var router = express.Router();
// Note the /api
router.get('/api', function(req, res, next) {
res.render('index', { title: 'API' });
});
module.exports = router;
Or you keep routes/index as it is but your change the way your register it in your main.js to this:
// ...
// Note the /api
app.use('/api', indexRouter);
app.use('/users', usersRouter);
// ...

How to export function from app.js and import it from another js-file?

I'm setting up a new server with node js and the framework express (Version 4.16). I want to route my Rest-Endpoints. In my route.js-file i want to call a function from app.js(my Server), but getting a Typeerror where the function, that i want to call from another file, is not a function.
Error:
TypeError: callFunction.getDataFromDb is not a function
at C:\Users\---\WebstormProjects\pwa_node_server\routes\recipes.js:7:18
at Layer.handle [as handle_request] (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:47:12)
My server:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var axios = require('axios');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var recipesRouter = require('./routes/recipes');
var cors = require('cors');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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(cors({credentials: true, origin: true}));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/recipes', recipesRouter);
// app.use('/poste-dein-rezept', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log("catch404");
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');
});
var getDataFromDb = function (res) { // This function to call in another file
};
module.export = {
getDataFromDb
};
module.exports = app;
My route-file:
var express = require('express');
========
var router = express.Router();
var callFunction = require('../app');
router.get('/', function(req, res, next) {
console.log('Recipes-Endpoint received Request');
callFunction.getDataFromDb(res);
});
module.exports = router;
I just want to call a function from another file.
You're using module.export. The Correct property name is module.exports, which you are also using.
One way to solve this is:
app.getDataFromDb = getDataFromDb;
module.exports = app;

node.js express app can't find jade view, 404 message responded

for my app i use node.js as backend and Express as framework. I use Netbeans as IDE and i get the following output.
Not Found
404
Error: Not Found
at /home/ingeborg/netbeans/GML/app.js:33:13
at Layer.handle [as handle_request] (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:317:13)
at /home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:335:12)
at next (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:275:10)
at /home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:635:15
at next (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:260:14)
at Function.handle (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:174:3)
at router (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:47:12)
I have the following data setup:
- node-modules
- public
- fonts
- images
- javascripts
- stylesheets
stylesheets.less
stylesheet.css
- routes
index.js
news.js
users.js
- views
index.jade
error.jade
news.jade
layout.jade
Gruntfile.js
app.js
gulpfile.js
package.json
the app.js looks like this
var news = require('./routes/news');
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');
...
app.use('/', index);
app.use('/index', index);
app.use('/news', news);
app.use('/users', users);
and this is my index.jade
h3
a(href="news") link
and this my news.jade
h3 test
.
The routing is realised over route files.
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/index', function(req, res, next) {
res.render('index');
});
module.exports = router;
the news.js router file is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('news', function(req, res, next) {
res.render('news');
});
module.exports = router;
The following circumstances are
the routing on the links "/" and "index" works as wanted.
the routing on "/news" or "news" (tested in the rounting, app.js and view file) not. I have no clue why the routing isn't working. I hope i haven't forgotten sth.
Thx,
Inge
Your code works for me.
/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 news = require('./routes/news');
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);
app.use('/news', news);
// 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/news.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('news');
});
module.exports = router;
The news route file is missing. There you have to render your jade.
var news = require('./routes/news');

New route in Express JS 404 error

Trying to add a new route to this Express app using the Express app generator. this is the 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 routes = require('./routes/index');
var users = require('./routes/users');
var parse = require('./routes/parse');
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('/', routes);
app.use('/users', users);
app.use('/parse', parse);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found - from app.js');
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;
The lines i added are:
var parse = require('./routes/parse');
app.use('/parse', parse);
Then in the /routes directory i added parse.js that contains:
var express = require('express');
var router = express.Router();
router.get('/parse', function(req, res, next) {
res.send('return from parse.js');
});
module.exports = router;
I can hit the / and the /users resource using a browser and i get the expected result. But when i try to hit /parse i get this 404:
Not Found - from app.js
404
Error: Not Found - from app.js
at /home/bitnami/parsecsvapi/app.js:32:13
at Layer.handle [as handle_request] (/home/bitnami/parsecsvapi/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:312:13)
at /home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:330:12)
at next (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:271:10)
at /home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:618:15
at next (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:256:14)
at Function.handle (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:176:3)
at router (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:46:12)
Try /parse/parse in the URL
If you would like to use /parse, please use / instead of /parse in /routes/parse.js
Please refer /routes/index.js & /routes/users.js.
TL;DR;
app.js
var parse = require('./routes/parse');
app.use('/parse', parse);
routes/parse.js
var express = require('express');
var router = express.Router();
// the URL pattern will be used in conjunction with how its is being used
// in this case it would be '/parse' (from app.js) + '/parse' (as used in the next line)
// resulting in '/parse/parse'
router.get('/parse', function(req, res, next) {
res.send('return from parse.js');
});
module.exports = router;

Resources