I have the following code (app.js):
var express = require('express');
var bodyParser = require('body-parser');
var mongoskin = require('mongoskin');
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(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var db = mongoskin.db('mongodb://#localhost:27017/testdb', {safe:true})
app.param('orders', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.use('/', routes);
app.get('/api/:orders', function(req, res, next) {
req.collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
Which works. What I'm going to do is to move the route (/api/:order) to another js file (routes/api.js). Here is the code:
var express = require('express');
var bodyParser = require('body-parser');
var mongoskin = require('mongoskin');
var routes = require('./routes/index');
var api = require('./routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var db = mongoskin.db('mongodb://#localhost:27017/testdb', {safe:true})
app.param('orders', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.use('/', routes);
app.use('/api', api);
The /routes/api.js file:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('respond with a resource');
});
// return all orders
router.get('/:orders', function(req, res, next) {
req.collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
module.exports = router;
I got the following error:
TypeError: Cannot call method 'find' of undefined
Can anybody tell me what's wrong with my code? Thanks.
I assume req.collection is undefined, because app.param('orders') is not executed for the other router.
Related
I've been trying to do a route in Express. For example one /about route, but it doesn't work.
var express = require('express');
var app = express();
var router = express.Router();
var moment = require('moment');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/', function (req, res) {
//some action
});
app.get('/time', function (req, res) {
//...
});
app.get('/about', function (req, res) {
res.send('about');
});
Currently after calling url/about I'm getting Cannot GET /about as a return and after some research I've got no idea how to resolve this issue. They even describe it that way in the official express docs.
Thank you in advance.
You have something like this in your code? :
app.listen(SERVER_PORT, function () {
console.log("Server successfully started on port:" + SERVER_PORT); });
We should have something like this:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
const app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/about', routes.about);
and also in the views folder: about.jade
I decided to take my routes out of my app.js and into their own seperate folders but now the site will load the handlebars file for index but not for about or contact - I am very confused and require help in exchange for a +1.
// Import the express module
var express = require('express');
var path = require("path");
var bodyParser = require("body-parser");
var index = require('./routes/index');
var about = require('./routes/about');
var contact = require('./routes/contact');
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
var app = express();
// Block the header from containing information
// about the server
app.disable('x-powered-by');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'handlebars');
app.engine('handlebars', handlebars.engine);
//set static folder
app.use(express.static(__dirname + '/public'));//allows access to public directory
//set bower folder
app.use('/bower_components', express.static(__dirname + '/bower_components'));//defines bower components directory
//body parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.set('port', process.env.PORT || 1337);// Defines the port to run on
app.use("/", index);
app.use("/about", about);
app.use("/contact", contact);
app.use(function(req, res){
res.type('text/html');
res.status(404);
res.render('404');
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500);
res.render('500');
});
app.listen(app.get('port'), function(){
console.log("Express started on http://127.0.0.1:" + app.get('port') + ' Press Ctrl+C to terminate');
})
This is the routes/index.js file:
var express = require("express");
var router = express.Router();
// Defines the base url
router.get('/', function(req, res, next){
// Point at the home.handlebars view
res.render('home');
});
module.exports = router;
And routes/about.js
var express = require("express");
var router = express.Router();
router.get('/about', function(req, res, next){
res.render('about');
});
module.exports = router;
When I go to localhost/contact, I get my 404 page and the same for /about.
The views are located in app/views, it worked when I had them down the pipeline in the app.js but since removing them it has broken. Any suggestions would be much appreciated!
This issue was with the routing itself. Say we are looking for /about with:
app.use("/about", about);
The app will then look into the routing folder of about and find the following.
var express = require("express");
var router = express.Router();
router.get('/about', function(req, res, next){
res.render('about');
});
module.exports = router;
And since I had another /about here in the router.get this would render at localhost/about/about
I am trying to export function within route file. Here is my code
app.js file
var express = require('express');
var bodyParser = require('body-parser');
var users = require('./routes/users');
var others=require('./routes/others')
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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('/others', others);
app.use('/users', users);
module.exports = app;
others.js file
var express = require('express');
var router = express.Router();
router.post("/test", function (req, res, next) {
res.send("success");
});
//Here i want to export function to users js file
var funDef=function(){
console.log("export a function")
}
moudle.exports=router;
How can I export or call funDef in users.js file. I tried the following way but it is not working
users.js file
var express = require('express');
var router = express.Router();
var readFun= require("./others.js");
router.post("/testUsers", function (req, res, next) {
res.send("suceess");
});
//getting undefined
readFun.funDef();
module.exports=router;
Can anyone guide me?
Try for the following:
function router() {}
router.prototype.funDef=function(){
console.log("export a function")
}
moudle.exports.router=router;
Another file:
var router = require('router').router;
var Router = new router();
Router.funDef();
EDIT:
// module.js
'use strict';
var temp = "this is a test";
module.exports.func = function() {
return temp;
}
// app.js
'use strict';
var module = require('./module');
console.log(module.func());
When I try to emit the 'ready' event from client on express.io, it shows an error that
{ route: [Function], broadcast: [Function] } 'req.io.route'
TypeError: Object # has no method 'ready
I am using express version express#4.12.4.
app.js is as shown below
var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express.io')();
app.http().io();
//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(__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);
and the index.js file is as below
app = require('express.io')()
app.http().io()
var router = app.Router();
/* GET home page. */
router.all('/', function(req, res, next) {
res.render('index', { title: 'Express' });
req.io.route('ready', function(res) {
console.log('tested..........');
})
});
module.exports = router;
client side code is as below
<script>
var socket;
$(document).ready(function(){
socket=io.connect(window.location.hostname);
socket.emit('ready');
});
</script>
</html>
please help me regarding this...
The router isn't a method on the return value of the constructor, it's exported with the module.
var express = require('express.io');
var app = express();
app.http().io()
var router = express.Router();
Also app.http().io() only needs to be called once, so remove it from your routes file.
Try
/* GET home page. */
router.all('/', function(req, res, next) {
app.io.route('ready', function(res) { //not req.io...
console.log('tested..........');
})
res.render('index', { title: 'Express' });
});
I am following Practical Node.js book. It is based on older version on express.js. The book is trying to build a blog. It has several different routes files. Ex- index.js, admin.js, article.js etc. This route classes are called from app.js. Ex:
app.use('/', routes.index);//// THE ISSUE IS HERE /////
app.get('/login', routes.user.login);
app.post('/login', routes.user.authenticate);
app.get('/logout', routes.user.logout);
app.get('/admin', routes.article.admin);
app.get('/post', routes.article.post);
app.post('/post', routes.article.postArticle);
Whenever someone tries to access '/', I am setting a collections object of artices and users in the request object.
var dbarticles = require('./db/articles.json');
var dbusers = require('./db/users.json');
app.use(function(req, res,next) {
if (!collections.articles || ! collections.users) return next(new Error("No collections."))
req.collections = collections;
return next();
});
app.use('/', routes.index);//// THE ISSUE IS HERE /////
The problem is that in index.js file, the value of req.collections is no available, I get 'undefined'. What am I missing. I have checked in the console.log, that the value is present in req.collections before the '/', route.index is hit.
Here's my app.js
var express = require('express');
var router = express.Router();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var methodOverride = require('method-override');
var routes = require('./routes');
var dbarticles = require('./db/articles.json');
var dbusers = require('./db/users.json');
var collections = {
articles: dbarticles,
users: dbusers
};
var logger = require('morgan');
var errorHandler = require('errorhandler');
var app = express();
app.locals.appTitle = 'blog-express';
//console.log(collections.articles || collections.users);
app.use(function(req, res,next) {
if (!collections.articles || ! collections.users) return next(new Error("No collections."))
req.collections = collections;
return next();
});
// 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());
app.use(methodOverride());
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
// Pages and routes
app.use('/', routes.index);
app.get('/login', routes.user.login);
app.post('/login', routes.user.authenticate);
app.get('/logout', routes.user.logout);
app.get('/admin', routes.article.admin);
app.get('/post', routes.article.post);
app.post('/post', routes.article.postArticle);
app.get('/articles/:slug', routes.article.show);
// REST API routes
app.get('/api/articles', routes.article.list);
app.post('/api/articles', routes.article.add);
app.put('/api/articles/:id', routes.article.edit);
app.delete('/api/articles/:id', routes.article.del);
app.all('*', function(req, res) {
res.sendStatus(404);
})
// catch 404 and forward to error handler
// error handlers
// development error handler
// development only
if ('development' == app.get('env')) {
app.use(errorHandler());
}
// production error handler
// no stacktraces leaked to user
//module.exports = router;
module.exports = app;
Here is my index.js
exports.article = require('./article');
exports.user = require('./user');
/*
* GET home page.
*/
exports.index = function(req, res, next){
console.log(".." + res.collections);
req.collections.articles.find({published: true}, {sort: {_id:-1}}).toArray(function(error, articles){
if (error) return next(error);
res.render('index', { articles: articles});
})
};
If some one needs to take a look at the code base of book, please check this github url - https://github.com/azat-co/practicalnode/tree/master/ch5/blog-express
Try changing app.use('/', routes.index) to app.get('/',routes.index)
If that doesn't work, try setting the middleware inline...
var setCollections = function (req, res,next) {
if (!collections.articles || ! collections.users) return next(new Error("No collections."))
req.collections = collections;
return next();
}
app.get('/', setCollections, routes.index)