Unable to load the webpage because the server sent no data.
Error code: ERR_EMPTY_RESPONSE
My local NodeJS setup becomes intermittently becomes unresponsive . When I refresh my computer it works fine but it keeps giving me the following message. Does anything in my code scream WRONG.
//dependencies
var path = require('path');
var express = require('express');
var http = require('http');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var schemas = require('./schemas/schemas');
//main config
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {
layout: false
});
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('BodySnatchingLizardPPL'));
app.use(express.session());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.configure('development', function () {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
//passport config
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
//mongoose
mongoose.connect('mongodb://demo2:demo2#ds033699.mongolab.com:33699/nicksdbthing');
require("fs").readdirSync("./routes_data_get/").forEach(function(file) {
require("./routes_data_get/" + file)(app);
});
require("fs").readdirSync("./routes_data_post/").forEach(function(file) {
require("./routes_data_post/" + file)(app);
});
require("fs").readdirSync("./routes_data_post/").forEach(function(file) {
require("./routes_data_post/" + file)(app);
});
app.listen(app.get('port'), function () {
console.log(("Express server listening on port " + app.get('port')))
});
Related
I have the follow - Generated initially by the Visual Studio Node Tools, uses Express and Jade as the client
/**
* Module dependencies.
*/
var express = require('express');
var fs = require('fs');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var https = require('https');
var path = require('path');
var passport = require('passport');
var googleStrategy = require('passport-google-oauth').OAuth2Strategy;
var loginHandler = require('./routes/Login.js');
var auth = require('./config/auth.js');
var googleSupport = require('./googleSupport.js');
var googleAuthority = auth.googleAuth;
var googleScopes = '';
// retrieve google scopes
googleScopes = googleSupport.discoverServiceScopes(auth.googleAuth);
// set up passport
passport.serializeUser(function (user,done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
passport.use(new googleStrategy({
clientID: googleAuthority.clientId,
clientSecret: googleAuthority.clientSecret,
callbackURL: googleAuthority.callbackUrl
},
function (accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));
var request = require('request');
var 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());
}
console.log('extracting service scopes');
app.get(passport.initialize());
app.get(passport.session());
app.get('/', routes.index);
app.get('/index', routes.index);
// google login support
// go to login page.
app.get('/googleLogin', passport.authenticate('google', { scope: [googleScopes] }),
function (req, res) {
res.redirect('/');
}
);
app.get('/AuthorizeGoogle', passport.authenticate('google', { failureRedirect: '/'}),
function (req, res) {
res.redirect('/');
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
The thing is when it validates the user I get the following
500 Error: passport.initialize() middleware not in use
at IncomingMessage.req.login.req.logIn (C:\Node\YourLivesN\YourLivesN\node_modules\passport\lib\http\request.js:44:34)
at Strategy.module.exports.strategy.success (C:\Node\YourLivesN\YourLivesN\node_modules\passport\lib\middleware\authenticate.js:228:13)
at verified (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js:179:18)
at Strategy._verify (C:\Node\YourLivesN\YourLivesN\app.js:41:12)
at C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js:195:22
at C:\Node\YourLivesN\YourLivesN\node_modules\passport-google-oauth\lib\passport-google-oauth\oauth2.js:115:7
at passBackControl (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:125:9)
at IncomingMessage. (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:143:7)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
Now I am assuming this is the same cause as this question passport.js passport.initialize() middleware not in use but cannot see what order the calls should be in my code.
So can anyone tell me what order to place the various parts of the code.
Thanks
Try changing this part
app.get(passport.initialize());
app.get(passport.session());
to
app.use(passport.initialize());
app.use(passport.session());
further reading on subject : Difference between app.use and app.get in express.js
, and I would suggest you separate passport configuration in a stand alone file and require it on paths that need authentication. Example tutorial : https://www.youtube.com/watch?v=zbfet_-Z5UQ&index=12&list=PLZm85UZQLd2Q946FgnllFFMa0mfQLrYDL
I'm new to Node.js. Trying to set up user account creation and log in using Passport. I can't ge it work. I am getting Unauthorized message although I am logging in with an existing user and pass. My code so far:
var express = require('express');
var http = require('http');
var path = require('path');
var request = require('request');
var app = express();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var MongoClient = require('mongodb').MongoClient;
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(app.router);
app.enable('trust proxy');
if ('development' == app.get('env')) {
}
var httpserver = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
/* Database has _id field but i guess i don't need to add anything here?*/
var Accoun = new Schema({
username: String,
password: String
});
/* Database collection is called 'users'*/
Accoun.plugin(passportLocalMongoose);
var Account = mongoose.model('users', Accoun);
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
mongoose.connect('xxxmyconnectionstring');
app.get('/', function(req, res) {
res.render('login.html');
});
app.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/myteam.html');
});
I need some expert help...
Regards,
I believe you need a successRedirect and failureRedirect in your app.post.
I know that there were asked similar questions to the issue:
I use formidable with express . And I see that 'fileBegin' event was not fired while 'file' event was fired.
Here are express definitions :
var app = express();
// all environments
process.env.port = 3001;
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(express.static(path.join(__dirname, 'public')));
Is there missing something in definitions? Thanks in advance
Update : upload handler :
function parseFormData(req,res,uploadDir){
var form = new formidable.IncomingForm();
var files = [];
try {
form.uploadDir = uploadDir;
form.parse(req, function() {
});
var logMsg;
form
.on('file',function(name, file) {
console.log('file found');
logMsg = util.format('Filename :%s\nFilesize: %s\nFilepath %s',file.name,file.size,file.path);
console.log(logMsg);
files.push(file);
})
.on('fileBegin',function(name, file) {
console.log('fileBegin file.name: '+file.name);
var targetFolder = path.dirname(file.path);
file.path = path.join(targetFolder,file.name);
console.log('new path: '+file.path);
})
.on('end', function() {
console.log(util.inspect(files));
res.writeHead(200);
res.end('done');
console.log('end');
});
}
catch(error){
res.end('done');
}
}
How do I get posted data from my api. I am using express 3.4.4
I am doing a resful api to accept posted data using node js and express
exports.mypost = function(req, res) {
console.log(req.body);
console.log(req.body.username);
console.log(req.body.name);
var user = new UserInfo({name:"dsd", username:"dsdsds"})
user.save();
res.send("user created");
}
and I post data use
curl --data "username=dsds&name=dsd" http://localhost:3000/mypost
I can see prints
{ username: 'dsds', name: 'dsd' }
dsds
dsd
But If I use
curl --form "username=dsds&name=dsd" http://localhost:3000/mypost
I see
{}
undefined
undefined
which means I didn't catch username and name from
req.body
How do I get the data from
curl --form "username=dsds&name=dsd" http://localhost:3000/mypost
I am posting my app.js:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var express = require('express');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
mongoose.connect('mongodb://localhost/data');
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var api = require('./controllers/api.js');
app.post('/mypost', api.mypost);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Add this:
App.use(express.bodyParser());
Make sure its set before all your routes.
You can use bodyParser method to get the data from a post request
// Configure server
app.configure(function() {
app.use(express.bodyParser());
}
I am trying to add in a subdomain with node.sj and Expressjs v3, but I keep getting 404 cannot get / when trying to load the subdomain.
var express = require('express'),
app = module.exports = express(),
MongoStore = require('connect-mongodb'),
server = require('http').createServer(app),
fs = require('fs'),
socket = require('./lib/sockets'),
flash = require('./middleware/flash');
app.configure('development', function () {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
app.configure(function () {
app.use(express.favicon(__dirname + '/public/domain.com/images/favicon.ico'));
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views/site');
app.set('view engine', 'ejs');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(flash());
app.use(app.router);
app.use(express.vhost(app.get('manager_vhost'), require('./subdomains/Manager')));
});
server.listen(3000);
socket.listen(server, sessionStore, app);
This is what I have in my Manager file
var express = require('express'),
manager = module.exports = express();
manager.configure(function () {
manager.use(express.static(manager.get('base_location') + '/public/'));
manager.engine('.html', require('ejs').__express);
manager.set('view engine', 'ejs');
manager.set('version', version);
});
Is there something I am doing wrong here?
Where are your routes defined? Try adding in a route and see what happens
manager.get('/', function (req, res) {
res.render('layout', {
title: 'Manager '
});
});