I am trying to make a app, in the app directory this is my app.js file. in the app.js I am requiring the router folder and exporting the Routes. But I am not able to render the index.jade using the Router instead i am getting error:
D:\Projects\socialApp\node_modules\express\lib\router\index.js:423
throw new TypeError(msg);
^
TypeError: Router.use() requires callback function but got a [object Undefined]
at D:\Projects\socialApp\node_modules\express\lib\router\index.js:423:13
at Array.forEach (native)
at Function.use (D:\Projects\socialApp\node_modules\express\lib\router\index
.js:419:13)
at D:\Projects\socialApp\node_modules\express\lib\application.js:178:21
at Array.forEach (native)
at Function.use (D:\Projects\socialApp\node_modules\express\lib\application.
js:175:7)
at Object.<anonymous> (D:\Projects\socialApp\app.js:22:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
D:\Projects\socialApp>
here is my app.js:
var express = require("express"),
passport = require("passport"),
passportLocal = require("passport-local"),
bodyParser = require("body-parser"),
cookieParser = require("cookie-parser"),
expressSession = require("express-session"),
jade = require("jade"),
mongoose = require("mongoose"),
routes = require('./routes'),
port = process.env.PORT || 3000,
app = express();
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
var routes = require('./routes/index')(passport); //i am calling here
app.use('/', routes); // not getting index.jade on screen.
app.listen(port, function(){
console.log('Port Listing to ' + port + ":" + __dirname);
});
here is what in the router folder and in the index.js:
var express = require('express'),
router = express.Router();
module.exports = function(passport){
router.get('/', function(req,res){
res.render('index'); //i am not getting index.jade from view folder getting error
});
}
any one figure-out the issue please?
You need to return router; at the end of your module.exports function.
Related
I'm new to node and having difficulty to get a simple express-handlebar to render a static html page:
require('./config/config');
const path = require('path');
const http = require('http');
const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');
const socketIO = require('socket.io');
const exphbs = require('express-handlebars');
var {mongoose} = require('./db/mongoose');
var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var {authenticate} = require('./middleware/authenticate');
var app = express();
var server = http.createServer(app);
var io =socketIO(server);
const port = process.env.PORT;
const publicPath = path.join(__dirname, './public');
app.use(bodyParser.json());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', exphbs);
app.use(express.static(publicPath));
app.get('/', (req, res) => {
res.render('index');
});
Instead of index.html sitting in views folder, I get this error:
Error: Cannot find module 'function exphbs(config) {
return create(config).engine;
}'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at new View (/home/me/nodechatapp/node_modules/express/lib/view.js:81:14)
at Function.render (/home/me/nodechatapp/node_modules/express/lib/application.js:570:12)
at ServerResponse.render (/home/me/nodechatapp/node_modules/express/lib/response.js:1008:7)
at app.get (/home/me/nodechatapp/server.js:37:7)
at Layer.handle [as handle_request] (/home/me/nodechatapp/node_modules/express/lib/router/layer.js:95:5)
at next (/home/me/nodechatapp/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/me/nodechatapp/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/me/nodechatapp/node_modules/express/lib/router/layer.js:95:5)
at /home/me/nodechatapp/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/me/nodechatapp/node_modules/express/lib/router/index.js:335:12)
at next (/home/me/nodechatapp/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/home/me/nodechatapp/node_modules/serve-static/index.js:121:7)
What could be wrong here? How can I fix it?
I'm pretty sure you are missing the app.engine() call in your server set up. Based on the docs you need:
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
You already use app.set for the view engine, but I think you need to call the prior line.
First time i have tried out to create a simple mean application.
I have followed the steps as per the below link
https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application#starting-our-node-application-packagejson
Finally i am getting the errors as
ReferenceError: mongoose is not defined
at Object.<anonymous> (C:\Users\Myname\Desktop\Mean sample\server.js:19:2)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
server.js
// modules =================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
// config files
var db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to our mongoDB database
// (uncomment after you enter in your own credentials in config/db.js)
mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('Magic happens on port ' + port);
// expose app
exports = module.exports = app;
How to fix it?
Can anyone please explain the steps to clear this issue
install mongoose
npm i mongoose --save
then import in your server.js file
var express = require('express');
var mongoose = require('mongoose') // import it
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
I see that many peoples have problem like mine but I don't find an answer.
I use Express 3.2.6 and I want to add Socket.io.
Server side :
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, index = require('./routes/index')
, http = require('http')
, path = require('path')
, nunjucks = require('nunjucks')
, mongoose = require('mongoose')
, validator = require('validator');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'nunjucks');
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')));
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var socket = io.connect();
I think that I make a lot of mistakes.
But I do not understant why node send me that :
var socket = io.connect();
^
TypeError: Object #<Server> has no method 'connect'
at Object.<anonymous> (C:\Users\Damien\workspace\project\app.js:35:17)
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:906:3
UPDATE
I changed for express.io
http://express-io.org/
But I have a problem. I have no error message but my server and my client do
not seem to communicate.
Client part :
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script type="text/javascript">
document.onload = function(){
var socket = io.connect("http://127.0.0.1:8080");
//Emit ready event.
socket.emit('ready');
//Listen for the talk event.
socket.on('talk', function(data) {
console.log(data);
});
};
</script>
Server part :
var app = require('express.io')()
var nunjucks = require('nunjucks')
var mongoose = require('mongoose')
var validator = require('validator');
var routes = require('./routes')
var index = require('./routes/index')
app.http().io()
app.set('view engine', 'nunjucks');
app.set('views', __dirname + '/views');
mongoose.connect( '' );
nunjucks.configure('views', {
autoescape: true,
express: app
});
var urlSchema = new mongoose.Schema({
long : String,
count : Number
}
);
//create model
var urlModel = mongoose.model('urls', urlSchema);
app.get('/', index.index);
//Setup the ready route, and emit talk event.
app.io.route('ready', function(req) {
req.io.emit('talk', {
message: 'io event from an io route on the server'
})
})
app.listen(8080);
I do not understand who there is nothing in client console.
I found the problem :
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
Must be
<script src="/socket.io/socket.io.js"></script>
I am trying to use passport to add user sessions on my webapp. I have configure my main js file as follow:
/**
* Module dependencies.
*/
var express = require('express');
var user = require('./server/routes/user');
var routes = require('./server/routes/index');
var http = require('http');
var path = require('path');
var app = express();
var passport = require('passport');
var flash = require('connect-flash');
require('./server/config/passport')(passport); // pass passport for configuration
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.configure(function(){
// required for passport
app.use(express.session({ secret: 'ilovesefounders' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
})
// routes ======================================================================
require('./server/routes/index')(app, passport); // load our routes and pass in our app and fully configured passport
routes.mount(app);
However when i try to launch it I get the following error:
require('./server/routes/index')(app, passport); // load our routes and pass i
^
TypeError: object is not a function
at Object.<anonymous> (/Path/app.js:38:33)
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
What's going wrong here?
I don't know how your index.js looks like but you probably did not export your function module.
Check if index.js looks something like this:
module.exports = function(app, passport) {
/* code */
};
And you don't need to require "./server/routes/index" again.
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
})