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;
Related
I am using passport.js for a basic log in/log out system. For some reason, the router.get('/signout', function(req, res)) is not being called when I run http://localhost:3000/auth/signout on Advanced rest client. Instead I am getting a Internal Server Error: 500. Login works just fine, but signout does not. Here is my app.js and authenticate.js:
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var passport = require('passport');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//Initialize models
require('./models/models.js');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);
var mongoose = require('mongoose');
//connect to mongodb
mongoose.connect("mongodb://localhost:27017/chirp-test");
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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(session({
secret: 'super duper secret'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session()); //This creates a unique has for our session
//Initialize Passport
var initPassport = require('./passport-init');
initPassport(passport);
app.use('/auth', authenticate);
app.use('/api', api);
// 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 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;
Authenticate.js
var express = require('express');
var router = express.Router();
module.exports = function(passport){
//sends successful login state back to angular
router.post('/success', function(req, res){
console.log('successful');
res.send({state: 'success', user: req.user ? req.user : null});
});
//sends failure login state back to angular
router.get('/failure', function(req, res){
res.send({state: 'failure', user: null, message: "Invalid username or password"});
});
//log in
router.post('/login', passport.authenticate('login', { failureRedirect: '/auth/failure' }),
function(req, res) {
//res.redirect('/auth/success');
res.send({state: 'success', user: req.user ? req.user : null});
});
//sign up
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//log out
router.get('/signout', function(req, res) {
console.log('Signing out...');
req.logout();
res.redirect('/');
});
return router;
}
You have registered nothing under "/". So when "auth/logout" call redirect to redirect("/"), I guess client is redirected but goes into your "error handler" which sends a 500 error...
I try to send a form with data in my nodejs app but I get "undefined" I am not sure does it matter but in console first I see "undefined", then POST. I have tried some "fixes" from the Internet like adding "type:'application/*+json', inflate: false" to app.use(bodyParser.json...) but nothing worked for me...
Undefined
POST /users/register 200 32.777 ms - 2346
this is my routes/users.js file:
var express = require('express');
var router = express.Router();
router.get('/register', function(req, res, next) {
res.render('register', {
'title': 'Register'
});
});
router.post('/register', function(req, res, next) {
console.log(req.body.name);
});
module.exports = router;
heres my jade file
form(method='post', action='/users/register', role='form')
.form-group
label Name
input.form-control(type='text', name='name', placeholder='Enter Name')
input.btn.btn-default(name='submit', type='submit', value='Register')
and app.js
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 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();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json({ type: 'application/*+json' }));
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
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);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
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
});
});
}
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Routing works fine what show setting up a title to "Register", but I have problems with sending post :/
You're configuring body-parser to only accept JSON request bodies, but your form is submitted in URL-encoded format (application/x-www-form-urlencoded).
For that, you need to add the correct parser:
app.use(bodyParser.urlencoded({ extended : true }));
More information, also on the meaning of extended : true, here.
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.
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'...
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;