Error: Failed to lookup view "error" in views directory - node.js

I have this error in my express.js project:
Error: Failed to lookup view "error" in views directory
I would like to redirect by a route into an html page.
I create a form that send to the route inserToDB a name and a surname.
I would like to redirect in the profile.ejs page but i find always this error.
I don't understand the reason. So i'll post my code in the hope that you can help me..
app.js
var routes = require('./routes/routes');
var users = require('./routes/users');
var app = express();
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')));
// view engine setup
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
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.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
console.log("index.ejs รจ caricata!");
res.render('index.ejs');
});
router.get('/profile', function(req, res) {
console.log("Ok ci siamo: profile caricata!");
res.render('profile.ejs');
});
router.get('/insertToDB', function(req, res) {
console.log(req.query.name + req.query.surname);
res.redirect("/profile");
});
module.exports = router;
index.ejs
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
Ciao loschi!
Inserisci i tuoi dati
<div>
Nome <input type="text" name="name" id="name"></input>
<br>
Cognome<input type="text" name="surname" id="surname"></input>
<br>
<input type="submit" name="Invia" id="enter"></input>
<script type="text/javascript" src="js/action.js"></script>
</div>
</body>
</html>
action.js
$("#enter").on("click", function(){
var name = $("#name").val();
var surname = $("#surname").val();
$.ajax({
type: "get",
url: "/insertToDB",
data:"name=" + name +"&surname="+ surname,
async:"true"
});
});

Try to change your engine setup in app.js to:
// view engine setup
app.engine('html', require('ejs').renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
Then change your error handler in app.js to:
// 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.ejs');
});
And don't forget to create a .ejs file called error.ejs in the views directory. This should fix the error.

--pls save the folders name view to views

Related

nodejs sessions after refresh a page

This is simple login form. I have validated a email, if email is not valid it gives an error( no problem here). After refreshing that page instead of showing login form it also shows error along with login form on that page.
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 hbs = require('express-handlebars');
var expressValidator = require('express-validator');
var expressSession = require('express-session');
var routes = require('./routes/index');
var app = express();
// view engine setup
//app.engine('hbs', hbs({extname: 'ejs'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'hbs');
// 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(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({secret: 'max', saveUninitialized: false, resave: false}));
app.use('/', routes);
// 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;
index.js file
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
console.log(req.session);
res.render('student_login', { success: req.session.success, errors: req.session.errors });
req.session.errors = null;
console.log(req.session);
});
router.get('/submit', function(req, res, next) {
req.check('e', 'Invalid email address').isEmail();
//req.check('p', 'Password is invalid').isLength({min: 4}).equals(req.body.confirmPassword);
var errors = req.validationErrors();
if (errors) {
console.log(req.session);
req.session.errors = errors;
req.session.success = false;
console.log(req.session);
} else {
console.log(req.session);
req.session.success = true;
console.log(req.session);
}
res.redirect('/');
});
module.exports = router;
student_login.ejs
<!DOCTYPE html>
<html >
<% if(success ){ %>
<h1>validation succesful</h1>
<% }
else{ %>
<ul>
<% if(errors) {%>
<h1> errors </h1>
<% } %>
</ul>
<h1>Login</h1>
<form action="/submit" method="get">
<input type="text" name="e" placeholder="Email" required="required" > <br>
<input type="password" name="p" placeholder="Password" required="required" > <br>
<button type="submit" >Let me in.</button>
</form>
<% } %>
</html>
The problem here is that you are saving your error in the session which means it will remain in the session unless you clear it out or the session ends.
What you need here is flash messages. These are similar messages stored in the session, but they are cleared once shown to the user, so they are shown only once.
I have used the connect-flash node module before. It is easy to set up and does the job perfectly.

Express.js request.body not working

I have a simple form for login, the problem is when i press "Submit", the request.body on server side is empty.I saw that bodyParser is a fundamental part but in my case it's declared before the routes, so i think the problem is another. this is my server page App.js
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: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
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 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');
});
app.listen(3000);
module.exports = app;
this is index.js
var express = require('express');
var router = express.Router();
function Login(req, res){
var mongoClient = require('mongodb').MongoClient;
mongoClient.connect('mongodb://localhost:27017/squaredDB', function(err, db) {
if(err) throw err;
db.collection('users').find({email: req.body.email}, function(err, data){
console.log(req.body);
});
});
}
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
Login(req, res);
res.render('app-home', { title: '' });
});
module.exports = router;
this is my jade template form:
form(method="post" action="/")
label Email
input(type="text" placeholder="Email")
label Password
input(type="password" placeholder="Password")
input(type="submit" value="login")
You're missing name attributes for your input fields in your template. Without those the browser won't submit them in the form.
Add a name attribute to your input field it will now be able to access the field via request like req.body.name
<form action="/", method="POST">
<input type="text" placeholder="name" name="name">
<button type="submit">Submit</button>
</form>

nodejs error 404 on post (not via url)

Whenever i try to submit from the index i get an error.
im trying to get the values from the username and password inputs.
this should be the code to handle the post:
app.post('/', function(req, res){
var username=req.body.username;
var password=req.body.password;
res.render("the username and password you posted:" +password+username);
});
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 routes = require('./routes/index');
var users = require('./routes/users');
var patienten = require('./routes/patienten');
var form = require('./routes/form');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
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: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use('/', routes);
app.use('/users', users);
app.use('/patienten', patienten);
app.use('/form', form);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.get("/", function(req, res) {
res.send("i am from /get");
});
app.get("/", function(req, res){
res.sendfile("/");
});
app.post('/', function(req, res){
var username=req.body.username;
var password=req.body.password;
res.render("the username and password you posted:" +password+username);
});
// 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 form.js
var express = require('express');
var router = express.Router();
var mysqlModel = require('mysql-model');
var request = require('request');
var ejs = require('querystring');
/* GET home page. */
router.get('/form', function(req, res) {
res.render('form', {
title: 'EPD - Login',
});
});
module.exports = router;
The form.ejs (the submit page)
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form action="/" method="GET">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" value="gogo">
</form>
</body>
</html>
This middleware for handling your 404, should be placed after your last route. Otherwise as per your code, all your hits will return 404.
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Besides, your form should send POST request not GET
<form action="/" method="POST">
Also, res.render is used to render a view. You can use res.send or res.json as you prefer.
app.post('/', function(req, res){
var username=req.body.username;
var password=req.body.password;
res.send("the username and password you posted:" +password+username);
});
You don't use res.render() for regular responses back to the client. Use res.send() instead. This is why you are receiving your error. res.render() is for use with a view engine in Express and sends back the rendered view template to the client. IE ejs in this case is the defined view engine and thats what the below code is doing
// view engine setup
// Tells express to render from the views directory
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
Your 404 handler should be your 2nd to last route in your express main file as it is a catch all for any routes that didn't match your defined routes since Express goes through routes Top-Down. Along with your 404 handler being defined in the wrong location within your Express app, you should examine possible collisions with your routes.
You have the following Router Middleware
app.use('/', routes);
and then subsequently the following GET route
app.get("/", function(req, res) {
res.send("i am from /get");
});
Depending on the contents of your routes file there could be collisions and the app.get() will never be executed.
You should set your routes up as follows:
app.use('/', routes);
app.use('/users', users);
app.use('/patienten', patienten);
app.use('/form', form);
// If you have a GET inside your 'routes' file
// from above, then this may never get called if
// it also contains a route for GET '/'
app.get("/", function(req, res) {
console.log('I am from get');
return res.render('index');
});
// My comment from above about your GET '/' would
// also apply to this POST route
app.post('/', function(req, res){
var username=req.body.username;
var password=req.body.password;
return res.status(200).send("the username and password you posted: " + password + ' ' + username);
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
return next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
return 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);
return res.render('error', {
message: err.message,
error: {}
});
});
You'll also need to change your HTTP Method specified in your form.ejs file from GET to POST
<form action="/" method="POST">

Keep getting undefined body when submitting POST request on a form

As the title says, I've been working at this for about 3 hours trying to figure out why the POST body for this is always undefined - no matter what I do. Could anyone look at my JADE/JS and help me figure out my issue?
JADE
doctype html
html(lang="en" ng-app)
head
meta(charset="utf-8")
meta(http-equiv="X-UA-Compatible", content="IE=edge")
meta(name="viewport", content="width=device-width, initial-scale=1")
// The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags
meta(name="description", content="")
meta(name="author", content="")
link(rel="icon", href="favicon.ico")
title Signin Template for Bootstrap
// Bootstrap core CSS
link(href="css/bootstrap.min.css", rel="stylesheet")
// Custom styles for this template
link(href="css/signin.css", rel="stylesheet")
// Just for debugging purposes. Don't actually copy these 2 lines!
//if lt IE 9
script(src="assets/js/ie8-responsive-file-warning.js")
// <script src="assets/js/ie-emulation-modes-warning.js"></script>
// HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries
//if lt IE 9
script(src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js")
script(src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js")
body
.container
form.form-signin(method="post", action="/")
h2.form-signin-heading(style="text-align:center;") Please sign in
label.sr-only(for="inputEmail") Student ID
input#inputID.form-control(type="text", name="userID", placeholder="User ID", required="", autofocus="")
label.sr-only(for="inputPassword") PIN:
input#inputPIN.form-control(type="password", name="userPIN", placeholder="Password", required="")
button.btn.btn-lg.btn-primary.btn-block(type="submit") Sign in
// /container
// IE10 viewport hack for Surface/desktop Windows 8 bug
script(src="assets/js/ie10-viewport-bug-workaround.js")
//AngularJS CDN
script(src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js")
server.js
//Add necessary dependencies (Express and MongoJS)
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('advisingApp',['advisingApp']); //sets the database for the project
//Test to make sure server is properly configured
/*app.get('/', function (request, response) {
response.send("Hello world from server.js!");
});*/
//Tell web app where to look for "static" files in directory - (it's looking in the default parent directory)
app.use(express.static(__dirname));
// app.get("/", function (request, response) {
// console.log("GET Request Received")
// db.advisingApp.find(function (err, docs) {
// console.log(docs);
// response.json(docs);
// });
// });
app.post("/", function (req, res) {
console.log("POST Request Received");
console.log(req.body);
});
app.listen(3000);
console.log("Server running smoothly on port 3000");
try 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 routes = require('./routes/index');
//var mongoose=require('mongoose');
//mongoose.connect('mongodb://localhost/test');
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.get("/",function(req,res){
res.render('view'); //i named ur given jade as view.jade
})
app.post("/", function (req, res) {
console.log("POST Request Received");
console.log(req.body);
});
// 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: {}
});
});
//
app.listen('3000',console.log('listening'));
// module.exports = app;

Angular Ui-Router isn't routing while using node.js

I am using angular ui router. The router seems to work perfect on the home page index.html. But any other navigation doesn't work.
Here is my stateprovider angular:
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("home", {
url: "/",
templateUrl: "../partials/home/index.html"
})
.state("login", {
url:"/login",
templateUrl: "../partials/account/login.html"
})
.state("register", {
url: "/register",
templateUrl: "../partials/account/register.html"
})
.state("values", {
url: "/values",
templateUrl: "../partials/test/values.html"
})
;
});
HTML in my main index.html:
<!--Content -->
<div class="container">
<div ui-view></div>
</div>
<!-- END Content -->
When I navigate the the page localhost:8080/login I get this:
I would think I shouldn't even be seeing this page if it can't find it. Shouldn't it redirect me back to "/" because of $urlRouterProvider.otherwise(). Besides that point though the template url /partials/account/login.html Does Exist.
I am somewhat new to node.js and I am curious if the note file server is trying to route and trumping my angular one? I am using http-server which is probably the most common one.
I am also using Express Node if that helps. And here is the code for app.js where I think the problem may be coming from:
var express = require('express');
var path = require('path');
var favicon = require('static-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', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
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;
I figured it out. Doing the below made it work.
app.use(function(req, res) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendfile(__dirname + '/public/index.html');
});
The entire app.js incase anyone is curious where it goes.
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendfile(__dirname + '/public/index.html');
});
app.use('/', routes);
/// 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;
Of course this will need to be in your angular code:
app.config(["$locationProvider", function($locationProvider) {
$locationProvider.html5Mode(true);
}]);
One thing to note that got me. You must restart the server for this to work. ctr+c then paste this code then restart server. Good luck
have you tried using the same directory for your partials :
moving partials/account/login.html" to partials/home/login.html"
Also, are you using your own server.js express configuration, or a yeoman fullstack ?
angular is clearly handling the routing, but it seems that nodejs is not finding the assets...
Be sure to have a specific task for serving partial files in your server.js
function serve_partial(req,res){
var stripped = req.url.split('.')[0];
var requestedView = path.join('./', stripped);
res.render(requestedView, function(err, html) {
if(err) {
res.render('404');
} else {
res.send(html);
}
});
}
function serve_index(req,res){
res.render('index');
}
// Angular Routes
app.get('/partials/*', serve_partial);
app.get('/*', serve_index);
for your case, it might me something as :
var express = require('express');
var path = require('path');
var favicon = require('static-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', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
function serve_partial(req,res){
var stripped = req.url.split('.')[0];
var requestedView = path.join('./', stripped);
res.render(requestedView, function(err, html) {
if(err) {
res.render('404');
} else {
res.send(html);
}
});
}
app.use('/partials/*', serve_partial);
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;
As i see you request to your node api which there isnt any route like /login and you get 404.
You should try localhost:8080/#/login

Resources