Node.js Route error - javascript

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();

Related

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;

Express Error: TypeError: Router.use() requires middleware function but got a Object

I am creating an upload/download app, i don't know why its only my app.js file is having this problem. I searched all other answers on the internet but still it did not solve the problem.
here is the code below:
var express = require('express');
var path = require('path'); // add path to set and get
var fs = require('fs'); // add filesystem
var connect = require('connect');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var connect = require('connect');
var http = require('http');
var routes = require('./routes/index');
var users = require('./routes/users');
//var upload = require('./routes/upload');
var app = express();
// 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(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')));
app.use(express.static('public'));
app.use(express.static('files'));
app.use('/', routes);
app.use('/users', users);
//app.use('/upload',upload);
// 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;
Thanks for your help.
check in your all files
make sure you don't miss export it
module.exports = router;
Router.use() at all times requires a Middleware function as an argument. Assuming your route to download some files from your server, it should Look similar to this.
var Router = express.Router();
function downloadFiles(request,response) {
// some code to dowload files
}
// The above function which takes request and response
// should be passed to Router.use()
Router.use(downloadFiles);
When you that error it means that what you passed to Router.use() is not a middleware function like downloadFiles.

404 Not Found when use nodejs to localhost

I made a simple login system using node and express 4.x. But I write localhost:3000 and see "Not Found 404".I think the problem is the epxress viersion is 4.x,however some code is express 3.x.
This is the error page :
Not Found
404
Error: Not Found
at app.use.res.render.message (C:\Users\Administrator\Desktop\front\node\node_web\blog\app.js:34:13)
at Layer.handle [as handle_request] (C:\Users\Administrator\Desktop\front\node\node_web\blog\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Administrator\Desktop\front\node\node_web\blog\node_modules\express\lib\router\index.js:312:13)
at C:\Users\Administrator\Desktop\front\node\node_web\blog\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\Users\Administrator\Desktop\front\node\node_web\blog\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\Administrator\Desktop\front\node\node_web\blog\node_modules\express\lib\router\index.js:271:10)
at cookieParser (C:\Users\Administrator\Desktop\front\node\node_web\blog\node_modules\cookie-parser\index.js:48:5)
at Layer.handle [as handle_request] (C:\Users\Administrator\Desktop\front\node\node_web\blog\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Administrator\Desktop\front\node\node_web\blog\node_modules\express\lib\router\index.js:312:13)
at C:\Users\Administrator\Desktop\front\node\node_web\blog\node_modules\express\lib\router\index.js:280:7
app.js
var path = require('path');
var express = require('express');
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 settings = require('./settings');
var users = require('./routes/users');
var session = require('express-sessi
on');
var MongoStore = require('connect-mongo')(session);
var app = express();
// view engine setup
app.set('port',process.env.PORT || 3000);
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(routes);
// app.use(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: {}
});
});
app.use(session({
secret: settings.cookieSecret,
key: settings.db,//cookie name
cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
store: new MongoStore({
db: settings.db,
host: settings.host,
port: settings.port
})
}));
app.use(express.static(path.join(__dirname,'public')));
routes(app);
module.exports = app;
index.js
module.exports = function(app) {
app.get('/', function (req, res) {
res.render('index');
});
app.get('/reg', function (req, res) {
res.render('reg', { title: '注册' });
});
app.get('/reg', function (req, res) {
});
app.post('/login', function (req, res) {
res.render('login', { title: '登录' });
});
app.post('/login', function (req, res) {
});
app.get('/post', function (req, res) {
res.render('post', { title: '发表' });
});
app.post('/post', function (req, res) {
});
app.get('/logout', function (req, res) {
});
};
In your app.js you are loading the routes but you are not telling express to use it. Put app.use('/', routes); right before the 404 catch.
PS: It's the line you've got commented.

Why is my server returning error 500 while trying to set a cookie?

I have an express v4 server with a route called admin. When the user post a password to the admin route, I want to respond by setting a cookie on the user's browser and sending a small json. For some reason, the server keeps returning error 500 when trying to respond. I'm assuming that this is something to do with the cookie as I can do "res.send()" without any problem. I'm new to express/nodejs so any help is appreciated.
admin.js
var express = require('express');
var router = express.Router();
var cookieParser = require('cookie-parser');
/* POST HANDLER */
router.post('/', function(req, res) {
var on = {'admin' : "on"};
res.cookie(cookie , 'cookie_on').send(on);
});
module.exports = router;
app.js
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 admin = require('./routes/admin');
var blogposts = require('./routes/blogposts');
var app = express();
// 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(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')));
app.use('/', routes);
app.use('/admin', admin);
app.use('/blogposts', blogposts);
// 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;
Dumb mistake: Cookie should have been 'cookie'...

Node.js & MongoDB - error 404 -not found

I'm trying to run an node.js and mongodb application...
see: http:// 93.188.162.100:3000/MelhoraCidade/ws/mcapp
but i'm getting the following error
Not Found
404
Error: Not Found
at app.use.res.render.message (/home/ladessa/files/MelhoraCidade/ws/mcapp/app.js:30:15)
at Layer.handle [as handle_request] (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:271:13)
at /home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:238:9
at Function.proto.process_params (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:313:12)
at /home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:229:12
at Function.match_layer (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:296:3)
at next (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:190:10)
at /home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:192:16
at Function.match_layer (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:296:3)
I used "express mcapp" to create the app....
EDIT app.js code:
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 app = express();
// 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')));
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;

Categories