I've an issue in NodeJS, i'm new to this.
I'm using nodeJS, express and JQTPL to follow a tutorial about calling the github API but the problem is on the Application configuration, particularly on engine definition.
var express = require('express'),
app = express(),
...
;
app.configure(function(){
app.set('view engine', 'html');
app.set('view options', {layout: false});
app.engine('.html', require('jqtpl').__express);
});
// When we go to the URL "/" we go the the index.html
app.get("/", function(req, res){
res.render("index");
});
app.get("/board", function(req, res) {
res.render("board");
})
the app.engine call fail, here is the error :
if ('function' != typeof fn) throw new Error('callback function required');
^
Error: callback function required
at Function.app.engine (/var/lib/stickshift/51d5872b5973ca8338000033/app-root/data/547742/node_modules/express/lib/application.js:173:38)
at Function. (/var/lib/stickshift/51d5872b5973ca8338000033/app-root/data/547742/app.js:15:9)
at Function.app.configure (/var/lib/stickshift/51d5872b5973ca8338000033/app-root/data/547742/node_modules/express/lib/application.js:392:61)
at Object. (/var/lib/stickshift/51d5872b5973ca8338000033/app-root/data/547742/app.js:12:5)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
I understand what's a callback.. etc.. but the only way to call app.engine i found is builded like this.
Thank you for your help !
jqtpl seems to be broken (at least the version in the NPM repo; the GH version might work better): it tries to determine the version of Express, but it uses a property (express.version) that doesn't exist anymore.
Here's a workaround:
var express = require('express');
var app = express();
app.configure(function(){
app.set('view engine', 'html');
app.engine('html', require('jqtpl/lib/express').render);
});
app.get("/", function(req, res){
res.render("index"); // this renders "views/index.html"
});
app.listen(3013);
Related
I have looked on the forums and have tried fixing everything I could, but still can't seem to get it to work. I am wanting to use router instead of having to use app.get. I have another project in which I am doing the same thing and it works just fine. So I am a little confused as to why this one isn't working. Thank you very much.
Here is my app.js:
var express = require("express");
var app = express();
var indexRoutes = require("./routes/index.js");
app.use("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use("/", indexRoutes);
app.listen(process.env.PORT, process.env.IP, function() {
console.log("server started on port : " + process.env.PORT);
});
Here is the route I am using:
var express = require("express");
var router = express.Router();
var multer = require("multer");
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads');
},
filename: function(req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({storage: storage}).single('userPhoto');
router.get("/", function(req, res) {
res.render("index");
});
router.post("/uploads", function(req, res) {
upload(req, res, function(err) {
if(err) {
return res.send("error uploading file");
}
res.end("file is uploaded");
});
});
module.exports = router;
This obviously isn't right:
app.use("view engine", "ejs");
It should be:
app.set("view engine", "ejs");
FWIW, if you closely look at the stack trace that accompanied the error, you would have found the exact line in app.js that triggered the error:
TypeError: Router.use() requires middleware function but got a string
at Function.use (/private/tmp/node_modules/express/lib/router/index.js:458:13)
at EventEmitter.<anonymous> (/private/tmp/node_modules/express/lib/application.js:220:21)
at Array.forEach (native)
at EventEmitter.use (/private/tmp/node_modules/express/lib/application.js:217:7)
at Object.<anonymous> (/private/tmp/t/app.js:5:5) <--- there!
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
i think you have to change this line:
app.use("/", indexRoutes);
with this:
app.use(indexRoutes);
more infos here: TypeError: Router.use() requires middleware function but got a Object
change this
app.use("view engine", "ejs");
to
app.set("view engine",'ejs');
I've been at this for hours and can't seem to figure out how to get it to work.
Here is the error I am getting when I run node dNode.js
Error: Cannot find module 'html'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/Users/ricky/LA/dNode.js:3:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
Here is what a portion of my code looks like
var express = require('express');
var mysql = require('mysql');
var html = require('html');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
var handlebars = require('express-handlebars').create({defaultLayout: 'main'});
app.use(bodyParser.json());
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', 3001);
app.use(express.static(__dirname + '/public'));
Try removing var html = require('html');or run
npm install html
First off, it is very hard to do try to solve your problem with so little given.
However, based on what you have given you need to specify your view folder and parse the engine to HTML.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('*', function(req, res){
res.render('index.html');
});
app.listen(app.get('port'), function() {
});
I installed nodejs using homebrew just now.
I then created a folder, and installed express:
npm install -g express
I then created a new project using:
express -H --css less --sessions foo
Now when I try and run the app:
node app.js
I get this:
/Users/blah/dev/testing/nodetest1/foo/node_modules/less-middleware/lib/middleware.js:50
throw new Error('Please update your less-middleware usage: http://goo.gl/Y
^
Error: Please update your less-middleware usage: http://goo.gl/YnK8p0
at module.exports.less.middleware (/Users/blah/dev/testing/nodetest1/foo/node_modules/less-middleware/lib/middleware.js:50:11)
at Object.<anonymous> (/Users/snad/dev/testing/nodetest1/foo/app.js:26:35)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
My app.js looks like:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('less-middleware')({ src: path.join(__dirname, 'public') }));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
I changed the line that was:
app.use(require('less-middleware')({ src: path.join(__dirname, 'public') }));
to:
app.use(require('less-middleware')(path.join(__dirname, 'public')));
and it works now. Strange how this was a brand new app with a fresh install of nodejs and express.
I commented out
app.use(require('less-middleware')({ src: path.join(__dirname, 'public') }));
entirely and achieved the same result. I feel that we are breaking functionality of some sort.
I've been banging my head against the wall. I've been doing the lynda.com tutorail on essential Node.js and I'm stuck at this point.
When i type nodemon server.js I get the error. I'm having problems exporting the db connection in node.js. Any hints? Is there a better way to debug then make a change and refresh in Node?
/Users/khebert/Sites/node/airline/node_modules/connect-mongo/lib/connect-mongo.js:87
this.db = new mongo.Db(options.mongoose_connection.db.databaseName,
^
TypeError: Cannot read property 'databaseName' of undefined
at new MongoStore (/Users/khebert/Sites/node/airline/node_modules/connect-mongo/lib/connect-mongo.js:87:60)
at module.exports (/Users/khebert/Sites/node/airline/app.js:22:10)
at Object.<anonymous> (/Users/khebert/Sites/node/airline/server.js:4:27)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
2 Jan 08:04:56 - [nodemon] app crashed - waiting for file changes before starting...
db.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/flights', function(err) {
if (err) console.log(err);
else console.log('DB success');
});
module.exports = mongoose.connections;
server.js
var http = require('http'),
flights = require('./data'),
db = require('./db'),
app = require('./app.js')(flights, db);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
app.js
module.exports = function(flights, db) {
/**
* Module dependencies.
*/
var express = require('express');
var MongoStore = require('connect-mongo')(express);
var routes = require('./routes')(flights);
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.session({
secret: 'keyboard cat',
store: new MongoStore({
mongoose_connection: db
})
}));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(function (req, res, next) {
res.set('X-Powerd-By','Flight Tracker');
next();
});
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
app.get('/flight/:number', routes.flight);
app.put('/flight/:number/arrived', routes.arrived);
app.get('/list', routes.list);
app.get('/arrivals', routes.arrivals);
return app;
};
It might be a problem with the 'express.bodyParser()', you have to define your connections AFTER all the configuration of your app.
In db.js,
module.exports = mongoose.connections;
change to:
module.exports = mongoose.connections[0];
You can just reuse the db object already instantiated by mongoose!
new MongoStore({
db: mongoose.connection.db
})
I'm using nodejs and mongodb in the back end for an app I'm working on. I'm using express to test the app, and I'm trying to use ejs to render my html files. However, I'm having the issue of my default view engine not being defined.
Here is my app.js:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var conf = require('./conf');
var app = express();
var mongoose = require('mongoose');
, Schema = mongoose.Schema
, ObjectId = mongooseSchemaTypes.ObjectID;
var UserSchema = new Schema({})
, User;
// all environments
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.engine('.html', require('ejs').renderFile());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Here is my package.json:
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.3.3",
"ejs":">= 0.0.1",
"mongoose-auth": ">= 0.0.12",
"mongoose": ">=2.4.8",
"everyauth": ">=0.2.28"
}
}
ERRORS:
Express
500 Error: Failed to lookup view "index"
at Function.app.render (/home/christian/node_modules/nave/create/node_modules/express/lib/application.js:494:17)
at ServerResponse.res.render (/home/christian/node_modules/nave/create/node_modules/express/lib/response.js:756:7)
at exports.index (/home/christian/node_modules/nave/create/routes/index.js:7:7)
at callbacks (/home/christian/node_modules/nave/create/node_modules/express/lib/router/index.js:161:37)
at param (/home/christian/node_modules/nave/create/node_modules/express/lib/router/index.js:135:11)
at pass (/home/christian/node_modules/nave/create/node_modules/express/lib/router/index.js:142:5)
at Router._dispatch (/home/christian/node_modules/nave/create/node_modules/express/lib/router/index.js:170:5)
at Object.router (/home/christian/node_modules/nave/create/node_modules/express/lib/router/index.js:33:10)
at next (/home/christian/node_modules/nave/create/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.methodOverride [as handle] (/home/christian/node_modules/nave/create/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:49:5)
Now when I try to run it my terminal outputs:
/home/christian/node_modules/nave/create/node_modules/express/lib/application.js:173
if ('function' != typeof fn) throw new Error('callback function required');
^
Error: callback function required
at Function.app.engine (/home/christian/node_modules/nave/create/node_modules/express/lib/application.js:173:38)
at Function.<anonymous> (/home/christian/node_modules/nave/create/app.js:26:9)
at Function.app.configure (/home/christian/node_modules/nave/create/node_modules/express/lib/application.js:392:61)
at Object.<anonymous> (/home/christian/node_modules/nave/create/app.js:23:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
Any help would be greatly appreciated.
The source of the error describes the requirements:
if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
Express expects that you either specify the view with its extension:
res.render('index.html');
Or specify a default view engine and name your views after it:
app.set('view engine', 'ejs');
// `res.render('index')` renders `index.ejs`
Regarding your edit:
if ('function' != typeof fn) throw new Error('callback function required');
The issue is with this line:
app.engine('.html', require('ejs').renderFile());
As the documentation demonstrates, app.engine() is expecting a function reference. You can do this by simply removing the () that call renderFile:
app.engine('.html', require('ejs').renderFile);
need to do all the app.set and app.use in an app.configure
try this
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.engine('.html', require('ejs').renderFile());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
});