Error: No default engine was specified and no extension was provided - node.js

I am working through setting up a http server using node.js and engine. However, I keep running into issues that I have little information on how to resolve I would appreciate some help solving this please.
Error: No default engine was specified and no extension was provided.
at new View (...\node_modules\express\lib\view.js:41:42)
at Function.app.render (...\node_modules\express\lib\application.js:484:12)
at ServerResponse.res.render (...\node_modules\express\lib\response.js:783:7)
at Layer.handle (...\app.js:123:7)
at trim_prefix (...\node_modules\express\lib\router\index.js:225:17)
at c (...\node_modules\express\lib\router\index.js:198:9)
at Function.proto.process_params (...\node_modules\express\lib\router\index.js:253:12)
at next (...\node_modules\express\lib\router\index.js:189:19)
at next (...\node_modules\express\lib\router\index.js:202:7)
at next (...\node_modules\express\lib\router\index.js:166:38)
Below is what I have set up to start up this engine.
var http = require('http');
var module = require("module")
var logger = require('morgan');
var express = require('express');
var app = module.exports = express();
var silent = 'test' == process.env.NODE_ENV;
var httpServer = http.createServer(app); // app middleware
app.enable('strict routing');
// app.all('*', function(req, res, next)/*** CORS support.*/
// {
// if (!req.get('Origin')) return next();// use "*" here to accept any origin
// res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
// res.set('Access-Control-Allow-Methods', 'GET, POST');
// res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
// res.set('Access-Control-Allow-Max-Age', 3600);
// if ('OPTIONS' == req.method) return res.send(200);
// next();
// });
app.set('views', __dirname + '/views'); // general config
app.set('view engine', 'html');
app.get('/404', function(req, res, next){
next();// trigger a 404 since no other middleware will match /404 after this one, and we're not responding here
});
app.get('/403', function(req, res, next){// trigger a 403 error
var err = new Error('not allowed!');
err.status = 403;
next(err);
});
app.get('/500', function(req, res, next){// trigger a generic (500) error
next(new Error('keyboard cat!'));
});
app.use(express.static(__dirname + '/public'));
//error handlers
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
// middleware with an arity of 4 are considered error handling middleware. When you next(err)
// it will be passed through the defined middleware in order, but ONLY those with an arity of 4, ignoring regular middleware.
function clientErrorHandler(err, req, res, next) {
if (req.xhr) {// whatever you want here, feel free to populate properties on `err` to treat it differently in here.
res.send(err.status || 500, { error: err.message });
}
else
{ next(err);}
};
// create an error with .status. we can then use the property in our custom error handler (Connect repects this prop as well)
function error (status, msg) {
var err = new Error(msg);
err.status = status;
return err;
};
function logErrors (err, req, res, next) {
console.error(err.stack);
next(err);
};
function errorHandler (err, req, res, next) {
res.status(500);
res.render('error', { error: err });
};
// Error handlers
// Since this is the last non-error-handling middleware use()d, we assume 404, as nothing else responded.
// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"
app.use(function(req, res, next){
res.status(404);
if (req.accepts('html')) {// respond with html page
res.render('404', { url: req.url });
return;
}
if (req.accepts('json')) {// respond with json
res.send({ error: 'Not found' });
return;
}
res.type('txt').send('Not found');// default to plain-text. send()
});
// error-handling middleware, take the same form as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).when connect has an error, it will invoke ONLY error-handling middleware.
// If we were to next() here any remaining non-error-handling middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware would remain being executed, however here
// we simply respond with an error page.
app.use(function(err, req, res, next){
// we may use properties of the error object here and next(err) appropriately, or if we possibly recovered from the error, simply next().
res.status(err.status || 500);
res.render('500', { error: err });
});
if (!module.parent) {// assigning to exports will not modify module, must use module.exports
app.listen(3000);
silent || console.log('Express started on port 3000');
};

The res.render stuff will throw an error if you're not using a view engine.
If you just want to serve json replace the res.render('error', { error: err }); lines in your code with:
res.json({ error: err })
PS: People usually also have message in the returned object:
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});

You are missing the view engine, for example use jade:
change your
app.set('view engine', 'html');
with
app.set('view engine', 'jade');
If you want use a html friendly syntax use instead ejs
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
EDIT
As you can read from view.js Express View Module
module.exports = View;
/**
* Initialize a new `View` with the given `name`.
*
* Options:
*
* - `defaultEngine` the default template engine name
* - `engines` template engine require() cache
* - `root` root path for view lookup
*
* #param {String} name
* #param {Object} options
* #api private
*/
function View(name, options) {
options = options || {};
this.name = name;
this.root = options.root;
var engines = options.engines;
this.defaultEngine = options.defaultEngine;
var ext = this.ext = extname(name);
if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
this.path = this.lookup(name);
}
You must have installed a default engine
Express search default layout view by program.template as you can read below:
mkdir(path + '/views', function(){
switch (program.template) {
case 'ejs':
write(path + '/views/index.ejs', ejsIndex);
break;
case 'jade':
write(path + '/views/layout.jade', jadeLayout);
write(path + '/views/index.jade', jadeIndex);
break;
case 'jshtml':
write(path + '/views/layout.jshtml', jshtmlLayout);
write(path + '/views/index.jshtml', jshtmlIndex);
break;
case 'hjs':
write(path + '/views/index.hjs', hoganIndex);
break;
}
});
and as you can read below:
program.template = 'jade';
if (program.ejs) program.template = 'ejs';
if (program.jshtml) program.template = 'jshtml';
if (program.hogan) program.template = 'hjs';
the default view engine is jade

Comment out the res.render lines in your code and add in next(err); instead. If you're not using a view engine, the res.render stuff will throw an error.
Sorry, you'll have to comment out this line as well:
app.set('view engine', 'html');
My solution would result in not using a view engine though. You don't need a view engine, but if that's the goal, try this:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//swap jade for ejs etc
You'll need the res.render lines when using a view engine as well. Something like this:
// 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);
next(err);
res.render('error', {
message: err.message,
error: {}
});
});

If you wish to render a html file, use:
response.sendfile('index.html');
Then you remove:
app.set('view engine', 'html');
Put your *.html in the views directory, or serve a public directory as static dir and put the index.html in the public dir.

instead of
app.get('/', (req, res) => res.render('Hellooooo'))
use
app.get('/', (req, res) => res.send('Hellooooo'))

Please replace
app.set('view engine', 'html');
with
app.set('view engine', 'ejs');

set view engine following way
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

If all that's needed is to send html code inline in the code, we can use below
var app = express();
app.get('/test.html', function (req, res) {
res.header('Content-Type', 'text/html').send("<html>my html code</html>");
});

The above answers are correct, but I found that a simple typo can also generate this error. For example, I had var router = express() instead of var router = express.Router() and got this error. So it should be the following:
// App.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended:false}));
// assuming you put views folder in the same directory as app.js
app.set('views', __dirname + '/views')
app.engine('ejs', ejs.renderFile);
app.set('view engine', 'ejs');
// router - wherever you put it, could be in app.js
var router = express.Router();
router.get('/', function (req,res) {
res.render('/index.ejs');
})

Just set view engine in your code.
var app = express();
app.set('view engine', 'ejs');

if you've got this error by using the express generator, I've solved it by using
express --view=ejs myapp
instead of
express --view=pug myapp

I just got this error message, and the problem was that I was not setting up my middleware properly.
I am building a blog in the MEAN stack and needed body parsing for the .jade files that I was using on the front end side. Here is the snippet of code from my "/middleware/index.js" file, from my project.
var express = require('express');
var morgan = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
module.exports = function (app) {
app.use(morgan('dev'));
// Good for now
// In the future, use connect-mongo or similar
// for persistant sessions
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(session({secret: 'building a blog', saveUninitialized: true, resave: true}));
Also, here is my "package.json" file, you may be using different versions of technologies.
Note: because I am not sure of the dependencies between them, I am including the whole file here:
"dependencies": {
"body-parser": "1.12.3",
"consolidate": "0.12.1",
"cookie-parser": "1.3.4",
"crypto": "0.0.3",
"debug": "2.1.1",
"express": "4.12.2",
"express-mongoose": "0.1.0",
"express-session": "1.11.1",
"jade": "1.9.2",
"method-override": "2.3.2",
"mongodb": "2.0.28",
"mongoose": "4.0.2",
"morgan": "1.5.1",
"request": "2.55.0",
"serve-favicon": "2.2.0",
"swig": "1.4.2"
}
Hope this helps someone! All the best!

You can use express-error-handler to use static html pages for error handling and to avoid defining a view handler.
The error was probably caused by a 404, maybe a missing favicon (apparent if you had included the previous console message). The 'view handler' of 'html' doesn't seem to be valid in 4.x express.
Regardless of the cause, you can avoid defining a (valid) view handler as long as you modify additional elements of your configuration.
Your options are to fix this problem are:
Define a valid view handler as in other answers
Use send() instead of render to return the content directly
http://expressjs.com/en/api.html#res.render
Using render without a filepath automatically invokes a view handler as with the following two lines from your configuration:
res.render('404', { url: req.url });
and:
res.render('500);
Make sure you install express-error-handler with:
npm install --save express-error-handler
Then import it in your app.js
var ErrorHandler = require('express-error-handler');
Then change your error handling to use:
// define below all other routes
var errorHandler = ErrorHandler({
static: {
'404': 'error.html' // put this file in your Public folder
'500': 'error.html' // ditto
});
// any unresolved requests will 404
app.use(function(req,res,next) {
var err = new Error('Not Found');
err.status(404);
next(err);
}
app.use(errorHandler);

Error: No default engine was specified and no extension was provided
I got the same problem(for doing a mean stack project)..the problem is i didn't mentioned the formate to install npm i.e; pug or jade,ejs etc. so to solve this goto npm and enter express --view=pug foldername. This will load necessary pug files(index.pug,layout.pug etc..) in ur given folder .

If you are using NestJS, to solve this issue you have to change your main.ts file.
Please consider using this example bellow:
Like this demo in NestJS - MVC
import { NestFactory } from '#nestjs/core';
import { NestFastifyApplication, FastifyAdapter } from '#nestjs/platform-fastify';
import { AppModule } from './app.module';
import { join } from 'path';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
app.useStaticAssets({
root: join(__dirname, '..', 'public'),
prefix: '/public/',
});
app.setViewEngine({
engine: {
handlebars: require('handlebars'),
},
templates: join(__dirname, '..', 'views'),
});
await app.listen(3000);
}
bootstrap();

Related

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;

Node.js / Express / Jade POST form 404s

So, I'm new to Javascript (and coding in general). To suppliment my education on Javascript, I thought I'd fool around with Node.js. Thinking I'd need a project I thought that I'd try to make a Dungeons & Dragons character creator. There are some out there already, but I'm needing a project, right?
So I made a form that takes the character name, and then instead of putting it to the console and/or displaying it on the page, I get a 404. I must be botching something simple here, so after a couple hours of trying to figure out what has to be a simple thing by myself and doing lots of search engine work, I thought I'd take it to the community.
Right now I have the base framework that you get from:
express --css myapp
Nothing fancy added. Here is my app.js (note the final lines with app.post:
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', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__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);
// 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;
app.post('/', function(req, res) {
console.log(req.body);
console.log('Character: ' + req.body.charactername);
res.send('Character Name: ' + req.body.charactername);
});
And finally, my jade file with the form.
extends layout
block content
h1= title
p Welcome to #{title}
form(method='post',action='/')
input(type='text',name='charactername')
input(type='submit')
Like I said, it is certainly something simple, but it's been driving me nuts and I can't seem to find that one document, webpage, howto, or tutorial that explains what I'm doing wrong here.
app.post('/', function(req, res) {}); is after your 404 error handling route. Move it so that it is before:
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
This will work as long as there is nothing conflicting in your other routes (app.use('/', routes)).

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

Where this undefined in Express.js console is coming from?

Useless middleware for testing purposes:
module.exports = function () {
return function rankick(req, res, next) {
if (Math.random() < 0.5) {
return next('Random kick...');
}
next();
};
};
Injected into a simple express app:
var express = require('express'),
http = require('http'),
path = require('path')
rankick= require('./rankick'),
util = require('util');
var app = express();
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(rankick()); // Using the middleware
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(function (req, res, next) {
res.end('Hello World!');
});
http.createServer(app).listen(app.get('port'));
When next() is invoked with the error string, console logs undefined followed by the 500 error:
undefined
GET / 500 28ms
GET / 200 4ms
undefined
GET / 500 5ms
Is it's this line in the errorHandler middleware. Maybe it expects to get a new Error('Random kick..')?
It's been a while since I used to default errorHandler so I am not 100% sure. In case it's not downvote and I'll remove this answer.
You should do
module.exports = function rankick(req, res, next) {
if (Math.random() < 0.5) {
console.log('Random kick...');
}
else
next();
};
Don't use return to pass the function. module.exports is the object that is passed when require is called.
Also next() is supposed to be called if you want to continue processing to next middleware. If you want to stop processing/kick request don't call next()

Redirect loop with node express.js

I have simple webpage with /about, /contact, /home and /lessons routes defined. All routes work okay except for /lessons. I instantly get a redirect loop (Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects).
Here's my main server.js code :
var port = process.env.PORT || 8888;
var app = require('./app').init(port);
var markdown = require('./markdown');
var lessons = require('./lessons.json').lessons;
// app.use(function(req,res,next) {
// console.log('adding lessons to locals');
// res.locals.date = new Date().toLocaleDateString();
// res.locals.lessons = lessons;
// next();
// });
// app.use(app.router);
app.get('/', function (req, res) {
console.log('controller is : home');
res.locals.controller = 'home';
res.render('home');
});
app.get('/:controller', function (req, res, next) {
var controller = req.params.controller;
console.log('controller is : '+ controller);
if (controller == 'about' || controller == 'contact') {
res.locals.controller = controller;
res.render(controller);
} else {
console.log('next was taken!');
next();
}
});
app.get('/lessons', function(req, res) {
res.locals.lessons = lessons;
console.log('controller is : lessons');
res.render('lessons');
});
app.get('/lessons/:lesson', function(req, res) {
console.log('controller is : lesson');
res.locals.controller = 'lessons';
res.send('gimmie the lesson');
});
/* The 404 Route (ALWAYS Keep this as the last route) */
app.get('/*', function (req, res) {
console.log('got 404 request to ' + req.url);
res.render('404');
});
and here's the app.jsfile which is used for server initialization:
var express = require('express');
var slashes = require('connect-slashes');
exports.init = function (port) {
var app = express();
app.use(express.static(__dirname + '/public'));
// add middleware to remove trailing slash in urls
app.use(slashes(false));
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.logger());
app.enable("jsonp callback");
if ('development' == app.get('env')) {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
app.use(express.logger({
format: ':method :url'
}));
}
if ('production' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(function (err, req, res, next) {
console.log('Oops, something went wrong');
res.render('500.ejs', {
locals: {
error: err
},
status: 500
});
});
app.listen(port);
console.log("Listening on port %d in %s mode", port, app.settings.env);
return app;
}
I have tried debugging the app with node-inspector but it's useless since the app doesn't seem to go into any of the app.gets to try to match. It immidiately gives me the error when I try to access localhost:8888/lessons
EDIT:
I think I have found the root of the problem :
My /public dir has a lessons folder
My /views dir has a lessons.ejs view
When I change /public/lessons into /public/lessons11 for example, the problem is resolved. Can someone explain to me what's express flow in the original scenario that causes the redirect loop ? also, what can I do to resolve it ?
Thanks
This happens:
a request for /lessons comes in;
the static middleware sees the public/lessons folder and assumes that's what the intended target is; because it's a folder, it will generate a redirect to /lessons/ (see below);
static middleware picks that request up again, but notices there's no index.html in that folder, and hands it off to the next middleware (connect-slashes);
the connect-slashes middleware removes the trailing slash and issues a redirect to /lessons;
the whole loop starts again;
You can prevent the static middleware from adding a trailing slash, which will fix your redirect loop I think:
app.use(express.static(__dirname + '/public', { redirect : false }));
You can try using express-redirect-loop middleware. It uses sessions and you can read more about it and implement it at https://github.com/niftylettuce/express-redirect-loop.

Resources