Cannot read property 'push' of undefined in node_modules - node.js

while running my first MEAN stack application i am getting this error:
\contactlist\node_modules\express\lib\router\index.js:502
this.stack.push(layer);
^
TypeError: Cannot read property 'push' of undefined
at Function.route (C:\Users\Mahima Kaushik\Desktop\contactlist\node_modules\express\lib\router\index.js:502:14)
at Function.proto. [as post] (C:\Users\Mahima Kaushik\Desktop\contactlist\node_modules\express\lib\router\index.js:509:22)
at Object. (C:\Users\Mahima Kaushik\Desktop\contactlist\routes\route.js:11:8)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Module.require (internal/modules/cjs/loader.js:1140:19)
at require (internal/modules/cjs/helpers.js:75:18)
at Object. (C:\Users\Mahima Kaushik\Desktop\contactlist\app.js:9:15)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
contactlist/app.js
var express = require('express');
var mongoos = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//connect to mongodb
mongoos.Mongoose.connect('mongodb://localhost:27017/contactlist');
//on connection
Mongoose.connection.on('connected',()=>{
console.log('connected to database mongodb #2717');
});
Mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('error in database connection:'+err);
}
});
//port number
const port = 3000
//adding middleware -cors
app.use(cors());
//boday-parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname,'public')));
//add routes
app.use('/api',route);
//testing
app.get('/',(req,res)=>{
res.send('contactlist');
});
app.listen(port,()=>{
console.log('server started at port:'+port);
});
contactlist/routes/route.js
const { Router } = require('express');
const express = require("express");
const router = express.Router();
//retrieving contacts
router.get('/contacts',(req,res,next) =>{
res.send('retrieving the contact list');
});
//add contacts
Router.post('/contact',(req , res, next)=>{
//logic
});
//delete contacts
Router.delete('/contact/:id',(req , res, next)=>{
//logic
});
module.exports = router;

You didn't create route correctly. The .get, .post and .delete are instance methods of Router instance, NOT static method. For more info, see Routing
routes/route.js should be:
const { Router } = require('express');
const router = Router();
//retrieving contacts
router.get('/contacts', (req, res, next) => {
res.send('retrieving the contact list');
});
//add contacts
router.post('/contact', (req, res, next) => {
//logic
});
//delete contacts
router.delete('/contact/:id', (req, res, next) => {
//logic
});
module.exports = router;

Related

nodeJS/Express TypeError : Cannot read property 'method' of undefined

Hello I am getting an error when trying to start my server. This is what it says :
D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:139
debug('dispatching %s %s', req.method, req.url);
^
TypeError: Cannot read property 'method' of undefined
at Function.handle (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:139:34)
at router (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:47:12)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\app.js:7:39)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Module.require (internal/modules/cjs/loader.js:1044:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\bin\www:7:11)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
My app.js file :
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var routes = require('./routes/index')(passport);
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var expressHbs = require('express-handlebars');
var mongoose =require('mongoose');
var app = express();
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost:27017/shopping', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.connection.on('error', err => {
throw 'failed to connect to MongoDB';
});
require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');
// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname:'.hbs'}))
app.set('view engine', '.hbs');
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'mysupersecret', resave: false, saveUninitialized: false}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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');
});
module.exports = app;
And my index.js file :
var express = require('express');
var router = express.Router();
var Product = require('D:/Other/Projects/Code/Powershell/shopping-cart/models/product');
var csrf = require('csurf');
//var passport = require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');
var passport = require ('passport');
var csrfProtection = csrf();
router.use(csrfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find(function(err, docs) {
var productChunks = [];
var chunkSize = 3;
for (var i = 0; i < docs.length; i += chunkSize) {
productChunks.push(docs.slice(i, i + chunkSize));
}
res.render('shop/index', { title: 'Shopping Cart', products: productChunks });
});
});
router.get('/user/signup', function (req, res, next) {
res.render('user/signup', {csrfToken: req.csrfToken()});
});
router.post('/user/signup', passport.authenticate('local.signup', {
successRedirect: '/user/profile',
failureRedirect: '/user/signup',
failureFlash: true
}));
router.get('/user/profile', function(req, res, next) {
res.render('user/profile');
});
module.exports = router;
Any hints on what could be the issue? I checked the lines that are being mentioned in the thrown error and can not find anything that is broken, and I have also checked other questions on this error, none that helped me. Any help is appreciated , thanks!
From the stack trace, it looks like the problem is caused by this line:
var routes = require('./routes/index')(passport);
If you look in your routes/index.js, you are exporting a router with:
module.exports = router;
Well, the problem is that you can't call router(passport). That's not a legit way to use a router. I can't tell what you were really trying to do with that. I would assume you want to hook your routes into the app with something like:
app.use(routes)
But, maybe you had some other intention there. In any case, router(passport) isn't something you can do.
FYI, it is a very useful skill to learn how to read these stack traces. You're typically looking to start at the top of the stack trace and go down line by line until you find a line of code that's in your own source file (your code that triggered this). Then, go examine that exact line with the context of what the eventual error was and see if you can then see what's wrong with that line of code or with the parameters used in that line of code.

app.use() requires a middleware function in express-edge

I'm creating blog using node js and following this tutorial https://vegibit.com/node-js-blog-tutorial/ but now I stuck it gives me error on app.use('express-edge') here is my code
const path = require('path');
const expressEdge = require('express-edge');
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = new express();
mongoose.connect('mongodb://localhost:27017/node-blog', {
useNewUrlParser: true
})
.then(() => 'You are now connected to Mongo!')
.catch(err => console.error('Something went wrong', err))
app.use(express.static('public'));
app.use(expressEdge);
app.set('views', __dirname + '/views');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', (req, res) => {
res.render('index');
});
app.get('/posts/new', (req, res) => {
res.render('create')
});
app.post('/posts/store', (req, res) => {
console.log(req.body)
res.redirect('/')
});
app.listen(4000, () => {
console.log('App listening on port 4000')
});
and my error looks like
[nodemon] starting node index.js
C:\Users\91762\Desktop\Blog\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\91762\Desktop\Blog\node_modules\express\lib\application.js:210:11)
at Object. (C:\Users\91762\Desktop\Blog\index.js:16:5)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
at Module.load (internal/modules/cjs/loader.js:798:32)
at Function.Module._load (internal/modules/cjs/loader.js:711:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:1014:10)
at internal/main/run_main_module.js:17:11
[nodemon] app crashed - waiting for file changes before starting...
Maybe the tutorial is out of date, newest version of express-edge does not export edge engine as default export, the package exports a object what includes config, engine.
You can follow package document if your node version support object destructuring.
...
const { engine } = require('express-edge');
...
app.use(engine);
...
Or, just change a little in your code:
app.use(expressEdge.engine); // instead of app.use(expressEdge);
Use it like a handler is the best choice.
app.use(expressEdge.engine);

Getting app.use require middleware even though I followed the documentation

I am getting app.use() requires a middleware function error when using Express edge package in npm. I am using this - https://github.com/ecrmnn/express-edge
I followed and read the documentation but I can't seem to find what else does the function require
Here is the code.
const path = require('path');
const expressEdge = require('express-edge');
const express = require('express');
const app = new express()
app.use(express.static('public'));
app.use(expressEdge);
app.set('views', `${__dirname}/views`);
app.get('/', (req, res) => {
res.render('index');
})
app.get('/about', (req, res) => {
res.sendFile(path.reso0lve(__dirname, 'pages/about.html'))
})
app.get('/post', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/post.html'))
})
app.get('/contact', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/contact.html'))
})
app.listen( 4000, () => {
console.log('App has started')
})
Here is the error:
E:\NODE-JS-BLOG\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (E:\NODE-JS-BLOG\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (E:\NODE-JS-BLOG\index.js:11:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
app.use() requires a middleware function[nodemon] restarting due to changes...
Did you mean expressEdge.engine ?
const path = require('path');
const {engine} = require('express-edge');
const express = require('express');
const app = new express()
app.use(express.static('public'));
app.use(engine);
app.set('views', `${__dirname}/views`);

Mongoose Schemea MissingSchemaError: Schema hasn't been registered for model

I'm building my first web app in the MEAN stack and am running into a little trouble with Mongoose. I pulled my code almost entirely from examples, and tried everything I found suggested on similar questions, but I still get the same error:
MissingSchemaError: Schema hasn't been registered for model "./models/Tests".
Use mongoose.model(name, schema)
at Mongoose.model (/Users/goldru/design-data/node_modules/mongoose/lib/index.js:332:13)
at Object.<anonymous> (/Users/goldru/design-data/routes/index.js:16:21)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/goldru/design-data/app.js:12:14)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/goldru/design-data/bin/www:7:11)
Code:
app.js:
//connect to db; require models
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/design-data-test');
var Test = require('./models/Tests');
var routes = require('./routes/index');
var users = require('./routes/users');
var express = require('express');
var app = express();
app.use('/', routes);
app.use('/users', users);
Tests.js:
var mongoose = require('mongoose');
var TestSchema = new mongoose.Schema({
name: String
});
mongoose.model('test', TestSchema);
index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/*GET test page.*/
router.get('/test', function(req, res, next) {
res.render('test', { title: 'Express' });
});
//set up routes
var mongoose = require('mongoose');
var Test = mongoose.model('./models/Tests');
router.get('/test', function(req, res, next) {
Test.find(function(err, tests) {
if(err) {
return next(err);
}
res.json(tests);
});
});
router.post('/test', function(req, res, next) {
var test = new Test(req.body);
Test.save(function(err,post) {
if(err) {
return next(err);
}
res.json(test);
});
});
module.exports = router;
Any suggestions would be really appreciated.
You name the model test:
mongoose.model('test', TestSchema);
So if you want to refer to it by name, you have to use the same name:
var Test = mongoose.model('test');
I would suggest renaming the model name to Test, which is Mongoose convention (not a requirement, though). I would also export it from your model file:
var mongoose = require('mongoose');
var TestSchema = new mongoose.Schema({
name: String
});
module.exports = mongoose.model('Test', TestSchema);

I'm not able to solve an error in nodejs using express framework

I'm a totally beginner with node.js and express framework. I'm following these tutorials.
Here's my code:
var fs = require("fs");
var config = JSON.parse(fs.readFileSync(__dirname + "\\config.json"));
var host = config.host;
var port = config.port;
var express = require("express");
var app = express.createServer();
app.get(__dirname + "\\",function(request, response){
response.send("Hello!");
});
app.listen(port,host);
And I'm having this error and I'm not able to solve it:
C:\Users\Fabio\Documents\GitHub\NodeJSProjects\ExpressSimpleServer\Server.js:7
var app = express.createServer();
^
TypeError: Object function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, proto);
mixin(app, EventEmitter.prototype);
app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
app.init();
return app;
} has no method 'createServer'
at Object.<anonymous> (C:\Users\Fabio\Documents\GitHub\NodeJSProjects\ExpressSimpleServer\Server.js:7:19)
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
I'm using node.js 0.10.26, express 4.0.0 and windows 8
See express project's reference. CreateServer is deprecated. Simply do this to create server and listen to a port
Var app = require("express")();
app.listen(3000);
SOLVED
I change the code according to expressjs guide
var fs = require("fs");
var config = JSON.parse(fs.readFileSync(__dirname + "\\config.json"));
var host = config.host;
var port = config.port;
var express = require("express");
var app = express();
app.get('/hello.txt', function(req, res){
res.send('Hello World');
});
var server = app.listen(port, function() {
console.log('Listening on port %d', server.address().port);
});

Resources