Swagger.js Cannot read property 'get' of null - javascript

I am trying to create a Swagger spec and application for my express api. My app.js file is:
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 tenants = require('./routes/tenants');
var models = require('./models.js');
var resources = require('./resources.js')
var app = express();
var swagger = require('swagger-node-express').createNew(app);
// 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')));
swagger.addModels(models);
swagger.addGet(resources.getTenantById);//This is where I am getting the error
swagger.setApiInfo({
title: "Swagger Sample App",
description: "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.wordnik.com or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters",
termsOfServiceUrl: "http://helloreverb.com/terms/",
contact: "apiteam#wordnik.com",
license: "Apache 2.0",
licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.html"
});
swagger.configureSwaggerPaths("", "api-docs", "")
swagger.configure("http://localhost:8002", "1.2.0");
app.use('/', routes);
app.use('/users', users);
app.use('/tenants',tenants);
// 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(8002);
My resources.js file is :
var sw = require('./node_modules/swagger-node-express/Common/node');
var swe = sw.swagger.errors;
var params = sw.paramTypes;
var url = require('url');
exports.getTenantById = {
'spec' : {
description : "Operations on Tenants",
path : "tenants/{tenantId}",
method : "GET",
nickname : "getTenantById",
summary : "Find Tenant by Id",
notes : "Returns a tenant by Id",
type : "Tenant",
produces : ["application/json"],
parameters : [params.path("tenantId","ID of the Tenant","string")],
responseMessages : [swe.invalid('tenantId')]
},
'action' : function(req,res){
if(!req.params.tenantId){
console.log("Tenants Id not provided");
return res;
}
var tenant = {
"id" : res.params.tenantId
}
res.send(JSON.stringify(tenant));
}
};
My package.json file:
{
"name": "myapp",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.10.2",
"cookie-parser": "~1.3.3",
"debug": "~2.1.1",
"express": "~4.11.1",
"jade": "~1.9.1",
"morgan": "~1.5.1",
"serve-favicon": "~2.2.0",
"swagger-node-express": "~2.0"
}
}
The link to swagger-node-express : https://github.com/swagger-api/swagger-node-express
And the error I am getting after running node app.js command:
Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:446
app[currentMethod](fullPath, function (req, res, next) {
^
TypeError: Cannot read property 'get' of null
at Swagger.addMethod (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:446:8)
at /Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:495:10
at Function.forOwn (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/node_modules/lodash/dist/lodash.js:1301:15)
at Swagger.addHandlers (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:493:5)
at Swagger.addGet.Swagger.addGET (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:520:8)
at Object.<anonymous> (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/app.js:31:9)
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)
I cannot understand why I am getting a null error?

I figured it out! It is a silly mistake. I forgot to add models.model in line 30 of app.js. I am importing models.js into the variable models but not using the exported variable models.model in addModels() on line 30 of app.js.
This question can be closed because it does not add anything useful to the community.

Related

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string Node.JS

I'm new on Node.js, and I try develop a simple movie api app with node.js and I created app with express-generator. I got this error and I couldn't handle it.
Firstly, I googled and I found github and stackoverflow I examined, but I couldn't resolve my issue.
firstly here error message :
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type object
at validateString (internal/validators.js:112:11)
at extname (path.js:1231:5)
at new View (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/view.js:56:14)
at Function.render (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/application.js:570:12)
at ServerResponse.render (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/response.js:1008:7)
at /Users/tugrul/Projects/Learning Projects/movie-api/app.js:45:7
at Layer.handle_error (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/index.js:315:13)
at /Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/index.js:335:12)
at next (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/index.js:275:10)
at /Users/tugrul/Projects/Learning Projects/movie-api/app.js:34:3
at Layer.handle [as handle_request] (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/index.js:317:13)
at /Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/index.js:335:12)
here is my package.json file:
{
"name": "movie-api",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "nodemon ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"mongoose": "^5.9.10",
"morgan": "~1.9.1"
}
}
and here is my app.js file:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const indexRouter = require('./routes/index');
const movieRouter = require('./routes/movie');
const directorRouter = require('./routes/director');
const app = express();
//mongodb connection
const db = require('./helper/db')();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/api/movies', movieRouter);
app.use('api/directors', directorRouter);
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});
// error handler
app.use((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:{message:err.message, code: err.code}});
});
module.exports = app;
and here is my director router file:
const express = require('express');
const router = express.Router();
//Models
const Director = require('../models/Director');
// Get All Movies
router.get('/', (req, res, next) =>{
res.json({message: 'Director APIs'});
});
module.exports = router;
And here is my movie router file:
const express = require('express');
const router = express.Router();
//Models
const Movie = require('../models/Movie');
// Get All Movies
router.get('/', (req, res) =>{
const promise = Movie.find({ });
promise.then((data)=>{
res.json(data);
}).catch((err)=>{
res.json(err)
});
});
//Top 10 List
router.get('/top10', (req, res) =>{
const promise = Movie.find({ }).limit(10).sort({ imdb_score: -1});
promise.then((data)=>{
res.json(data);
}).catch((err)=>{
res.json(err)
});
});
//Add new movie
router.post('/add-movie',(req,res,next)=>{
//const {title,imdb_score,category,country,year} = req.body;
const movie = new Movie(req.body);
const promise = movie.save();
promise.then((data)=>{
res.json(data);
}).catch((err)=>{
res.json(err);
});
});
// Get Movie From ID
router.get('/:movie_id',(req,res,next)=>{
const promise = Movie.findById((req.params.movie_id));
promise.then((movie)=>{
if(!movie){
console.log(movie);
next({message : 'This movie can not found!', code:404});
}else{
res.json(movie);
}
}).catch((err)=>{
res.json(err);
});
});
//Update Movie
router.put('/:movie_id',(req,res,next)=>{
const promise = Movie.findByIdAndUpdate(
req.params.movie_id,
req.body,
{
new: true
});
promise.then((movie)=>{
if(!movie){
console.log(movie);
next({message : 'This movie can not found!', code:404});
}else{
res.json(movie);
}
}).catch((err)=>{
res.json(err);
});
});
//Delete movie
router.delete('/:movie_id',(req,res,next)=>{
const promise = Movie.findByIdAndRemove(
req.params.movie_id,
req.body);
promise.then((movie)=>{
if(!movie){
console.log(movie);
next({message : 'This movie can not found!', code:404});
}else{
res.json({status: 1});
}
}).catch((err)=>{
res.json(err);
});
});
// get movies between two years
router.get('/between/:start_year/:end_year',(req,res,next)=>{
const {start_year,end_year} = req.params;
const promise = Movie.find(
{
// gte = ">=", lte = "<="
year: { "$gte": parseInt(start_year), "$lte": parseInt(end_year)}
}
);
promise.then((movie)=>{
if(!movie){
console.log(movie);
next({message : 'This movie can not found!', code:404});
}else{
res.json(movie);
}
}).catch((err)=>{
res.json(err);
});
});
module.exports = router;
When I try to access http://localhost:3000/api/directors I get this error. Why? How can I handle it?
Could you help me please?
The problem is the following line:
res.render({error:{message:err.message, code: err.code}});
According to the docs, render expects the first parameter to be a path to the html-page to be rendered. Assuming there's a file called error in your views directory, changing it to
res.render('error', {error:{message:err.message, code: err.code}});
should fix the problem.
Regarding the second question from the comments:
The problem here is your middleware:
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});
Basically every request will result in an error, as you set up an ordinary middleware which will also be executed on a successful request. So you can probably just remove this middleware, as you have error handlers set up anyway.

throw new TypeError('app.use() requires middleware functions');

I am following an online course on Nodejs and was trying to implement basic authentication in my express application. But I am getting error on app.use(new localStrategy(User.Authenticate()); I have tried reinstalling the 'passport-local'. Why this error keeps persisting ?
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
passport = require('passport'),
User = require('./models/user'),
bodyParser = require('body-parser'),
localStrategy = require('passport-local'); ;
passportLocalMongoose = require('passport-local-mongoose');
mongoose.connect('mongodb://localhost/auth_DB');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('images'));
app.use(require('express-session')({
secret: 'pppppqpqsda dasdqw ksndfkjnzmmuawt8ikweabmdsfj a',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
// body...
res.render('home');
});
app.get('/secret', function (req, res) {
// body...
res.render('secret');
});
app.get('/register', function (req, res) {
// body...
res.render('signup');
});
app.post('/register', function (req, res) {
User.register(new User({username: req.body.username}), req.body.password, function(err, user){
if(err){
console.log(err);
return res.render('signup');
}
passport.authenticate('local')(req, res, function(){
res.redirect('/secret');
});
});
});
app.get('/login', function (req, res) {
// body...
res.render('signin');
});
app.post('/login', passport.authenticate('local',
{successRedirect: '/secret',
failureRedirect: '/login'} ),
function(req, res){});
app.listen(3000, function(){
console.log('Server Started!');
});
Package.json :-
{
"name": "test-auth",
"version": "1.0.0",
"description": "Testing the authentication",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Rishabh & Colt",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"ejs": "^2.5.6",
"express": "^4.15.2",
"express-session": "^1.15.2",
"mongoose": "^4.9.7",
"passport": "^0.3.2",
"passport-local": "^1.0.0",
"passport-local-mongoose": "^4.0.0"
}
}
User.js:-
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var userSchema = new mongoose.Schema({
username: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', userSchema);
Error:-
C:\Users\Atom\Project\testAuth\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires middleware functions');
^
TypeError: app.use() requires middleware functions
at EventEmitter.use (C:\Users\Atom\Project\testAuth\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (C:\Users\Atom\Project\testAuth\app.js:37:5)
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)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3
You code has some typo. localStrategy is not a middleware for express. It can be used with passport.
Replace
app.use(new localStrategy(User.authenticate()));
with
passport.use(new localStrategy(User.authenticate()));
You seem to require the wrong module
You are requiring local strategy this way
LocalStrategy = require('passport-local');
but in docs, you need to add '.Strategy'
http://passportjs.org/docs/configure
LocalStrategy = require('passport-local').Strategy;

Can't get a proper error from passport-linkedin strategy

I can't seem to get some good feedback to properly diagnose the problem.
Right now I am getting a generic error I set up in the app.js file
Here is the error:
Not Found
404
Error: Not Found
at /Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/app.js:48:13
at Layer.handle [as handle_request] (/Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/node_modules/express/lib/router/index.js:312:13)
at /Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/node_modules/express/lib/router/index.js:330:12)
at next (/Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/node_modules/express/lib/router/index.js:271:10)
at /Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/node_modules/express/lib/router/index.js:618:15
at next (/Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/node_modules/express/lib/router/index.js:256:14)
at Function.handle (/Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/node_modules/express/lib/router/index.js:176:3)
at router (/Users/avonproductsinc/Dropbox/developer_folder/oauth-passport-securing-application/securing-app-OAuth-passport/node_modules/express/lib/router/index.js:46:12)
This is my code in my linkedin strategy:
var passport = require('passport');
var LinkedInStrategy = require('passport-linkedin').Strategy;
module.exports = function() {
passport.use(new LinkedInStrategy({
consumerKey: '77z7e2bq34ad0w',
consumerSecret: 'ajTJfuNTxLnDGlCK',
callbackURL: "http://127.0.0.1:3000/auth/linkedin/callback"
},
function(token, tokenSecret, profile, done) {
var user = {};
// user.email = profile.emails[0].value;
// user.image = profile._json.image.url;
user.displayName = profile.displayName;
user.linkedin = {};
user.linkedin.id = profile.id;
user.linkedin.token = tokenSecret;
done(null, user);
}));
};
And this is in my auth.js file
var express = require('express');
var passport = require('passport');
var router = express.Router();
router.route('/linkedin')
.get(passport.authenticate('linkedin'));
router.route('/linkedin/callback')
.get(passport.authenticate('linkedin', {
successRedirect: '/users',
failureRedirect: '/error'
}));
Any help is appreciated, naturally!
Update Jan 15 2017
app.js code:
var express = require('express'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
passport = require('passport'),
session = require('express-session'),
mongoose = require('mongoose'),
routes = require('./routes/index'),
users = require('./routes/users'),
auth = require('./routes/auth'),
app = express(),
db = mongoose.connect('mongodb://localhost/socialAgg');
app.use(require('node-sass-middleware')({
src: path.join(__dirname, 'public'),
dest: path.join(__dirname, 'public'),
indentedSyntax: true,
sourceMap: true
}));
// 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(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')));
// setting up passport middlware
app.use(session({secret: 'anything'}));
require('./config/passport')(app);
app.use('/', routes);
app.use('/users', users);
app.use('/auth', auth);
// 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;

typeerror: app.use() requires middleware function

I am learning node.js with express template engine, I am following udemy course "learn node.js by building 10 projects", while following a lecture when professor run npm start localhost:3000 starts while mine pops up error indicating app.use requires middleware function
I have tried matching code and its same. Please help me to resolve the error i have been stuck here for hours tried a lot of edits but its not working for me.
When I am trying to run 'npm start' following error pops up
TypeError: app.use() requires middleware functions
Here is app.js code:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
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');
//Handle File Uploads
app.use(multer({
dest: './uploads'
}));
// 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
}));
//Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialied: true,
resave: true
}));
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while (namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function(req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
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;
Here is package.json file
{
"name": "nodeauth",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.12.4",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"express": "~4.12.4",
"jade": "~1.9.2",
"morgan": "~1.5.3",
"serve-favicon": "~2.2.1",
"mongodb": "*",
"mongoose": "*",
"connect-flash": "*",
"express-validator": "*",
"express-session": "*",
"express-messages": "*",
"passport": "*",
"passport-local": "*",
"passport-http": "*",
"multer": "*"
}
}
Here is updated app.js (after removing multar)
var express = require('express'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
expressValidator = require('express-validator'),
session = require('express-session'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
bodyParser = require('body-parser'),
flash = require('connect-flash'),
mongo = require('mongodb'),
mongoose = require('mongoose'),
db = mongoose.connection,
routes = require('./routes/index'),
users = require('./routes/users'),
app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// handle file uploads
//multer delted
// 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 }));
// handle express sessions
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
// passport
app.use(passport.initialize());
app.use(passport.session());
// validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg : msg,
value: value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// flash
app.use(flash());
// express messages
app.use(function(req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('*', function(req, res, next) {
res.locals.user = req.user || null;
next();
});
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: {}
});
});
//Express server
var http = require('http');
var server = http.createServer(app);
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000, 'localhost');
server.on('listening', function() {
console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});
module.exports = app;
Thank You
It worked in this way. delete this line,
app.use(multer({ dest: './uploads' }));
and use it as,
var multer = require('multer');
var upload = multer({ dest: './uploads' });
I'm too following the same course
Change:
//Handle File Uploads
app.use(multer({
dest: './uploads'
}));
For something like:
app.use(multer({dest:'./uploads/'}).single('singleInputFileName'));
or
app.use(multer({dest:'./uploads/'}).array('multiInputFileName'));
And be aware to have something like:
<form action="/postPhotos" enctype="multipart/form-data">
<input type="file" name="singleInputFileName">
<input type="submit" value="Upload photo">
</form>
for the first case, or:
<form action="/postPhotos" enctype="multipart/form-data">
<input type="file" name="multiInputFileName" multiple>
<input type="submit" value="Upload photo">
</form>
For the second one, in your html.
This worked with me:
app.use(multer({
dest: path.join(__dirname, 'public/upload/temp')
}).any());
I was also doing that course & ran into the same problem. I resolved the error by following the Multer usage instructions from their github: https://github.com/expressjs/multer
Here is the code from their README:
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
& here is the code I used to overcome the error while doing that tutorial:
var multer = require('multer');
var upload = multer({ dest: './uploads' });
Hope it helps :)
you can simply use :
app.set(multer({dest: "./uploads"}));
it works for me too.
change only this line
app.use(multer({dest:'./uploads'}));
to
var upload =multer({dest:'./uploads'});
Replacing app.use(multer({dest:'./uploads'}));
to
var upload = multer({dest:'./uploads'});
worked for me.

Node.js Route error

Absolute beginner in node.js I was making that routes file which is below
productCategoryRouteConfig.js
function productCategoryRouteConfig(app){
this.app = app;
this.routesTable = [];
this.init();
}
productCategoryRouteConfig.prototype.init = function(){
this.addRoutes();
this.processRoutes();
}
productCategoryRouteConfig.prototype.processRoutes = function(){
this.routesTable.forEach(function(route){
if(route.requestType === 'get')
{
this.app.get(route.requestUrl, route.callbackFunction)
}
});
}
productCategoryRouteConfig.prototype.addRoutes = function(){
this.routesTable.push({
requestType: 'get',
requestUrl: '/createProductCategory',
callbackFunction: function(request, response){
response.render('createProductCategory', {title: "Create Product Category"});
}
});
}
module.exports = productCategoryRouteConfig;
my app.js file is below
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 productCategoryRoute = require('./routes/productCategoryRouteConfig');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/bower_components', express.static(__dirname + '/bower_components'));
// 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);
/******BEGIN CUSTOM ROUTES*********/
new productCategoryRoute(app)
/******END CUSTOM 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: {}
});
});
but when run the npm server with this command DEBUG=nodecrud:* ./bin/www I get the following errors
/home/sharif/Sites/node/angularmysqlnode/nodecrud/routes/productCategoryRouteConfig.js:22
this.app.get(route.requestUrl, route.callbackFunction)
^
TypeError: Cannot read property 'get' of undefined
at /home/sharif/Sites/node/angularmysqlnode/nodecrud/routes/productCategoryRouteConfig.js:22:21
at Array.forEach (native)
at productCategoryRouteConfig.processRoutes (/home/sharif/Sites/node/angularmysqlnode/nodecrud/routes/productCategoryRouteConfig.js:18:22)
at productCategoryRouteConfig.init (/home/sharif/Sites/node/angularmysqlnode/nodecrud/routes/productCategoryRouteConfig.js:13:10)
at new productCategoryRouteConfig (/home/sharif/Sites/node/angularmysqlnode/nodecrud/routes/productCategoryRouteConfig.js:8:10)
at Object.<anonymous> (/home/sharif/Sites/node/angularmysqlnode/nodecrud/app.js:39:1)
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)
I have no clue why this error is coming up can you help me to fix this error please
any idea?
You are not passing in app in this line-
var productCategoryRoute = require('./routes/productCategoryRouteConfig');
do this
var productCategoryRoute = require('./routes/productCategoryRouteConfig')(app);
and put it after
var app = express();

Categories