My code works fine on localhost. But when I push to heroku. I'm fairly new to node.js.
Here is my app.js file.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app).listen(process.env.PORT || 8080);;
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 mongoose = require('mongoose');
var io = require('socket.io').listen(server);
var nicknames = [];
io.configure(function() {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
io.sockets.on('connection', function(socket) {
io.sockets.emit('usernames', nicknames);
socket.on('chat message', function(data) {
io.sockets.emit('chat message', {
msg: data,
nick: socket.nickname
});
});
socket.on('new user', function(data, callback) {
if (nicknames.indexOf(data) != -1) {
callback(false);
} else {
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
io.sockets.emit('usernames', nicknames);
}
});
socket.on('disconnect', function(data) {
if (!socket.nickname) return;
nicknames.splice(nicknames.indexOf(socket.nickname), 1);
io.sockets.emit('usernames', nicknames);
});
});
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
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
app.get('/', function(req, res) {
res.render('index.hjs');
});
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;
I get this error when I run the actual website.
Application Error
An error occurred in the application and your page could not be served. Please try again in a few moments.
If you are the application owner, check your logs for details.
I'm creating a public chat but for whatever reason I cannot get the application running. How can I fix this problem?
Related
Im having trouble connecting Node.js application with sql database.
Error occurs is "req.getConnection is not a function".
I am trying to get data from the database the moment I click on a certain page (eg.users).
My code is as below
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 flash = require('express-flash');
var session = require('express-session');
var expressValidator = require('express-validator');
var methodOverride = require('method-override');
var connection = require('express-myconnection');
var mysql = require('mysql');
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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({secret:"mysecretpass"}));
app.use(flash());
app.use(expressValidator());
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use(methodOverride(function(req, res){
if (req.body && typeof req.body === 'object' && '_method' in req.body)
{
var method = req.body._method;
delete req.body._method;
return method;
}
}));
/*-----------------------------------------
* Connection peer, register as middleware
* type koneksi:single,pool and request
-----------------------------------------*/
app.use(
connection(mysql,{
host:'localhost',
user:'root',
password:'',
port:3306,
database:'stores'
},'single')
);
// 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;
routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('dashboard', { title: 'Dashboard' });
});
router.get('/admin_users', function(req, res, next) {
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM users',function(err,rows)
{
if(err)
var errornya = ("Error Selecting : %s ",err );
req.flash('msg_error', errornya);
res.render('admin_users',{title:"Admin Users",data:rows});
});
//console.log(query.sql);
});
});
module.exports = router;
You are adding the express-myconnection middleware after your routes middleware. Middleware is executed in the order it is added, and as such the getConnection function is not defined on the req object until after your express-myconnection middleware is executed.
Simply move the connection middleware above the usage of routes, ie.
app.use(
connection(mysql,{
host:'localhost',
user:'root',
password:'',
port:3306,
database:'stores'
},'single')
);
app.use('/', routes);
app.use('/users', users);
Am developing with nodejs and am sending a post request for a form submission, the first request throws server error 500 but subsequent click of buttons works perfectly. Below is my codes. What am I doing wrongly?
Ajax
$(document).ready(function (e) {
$("#group_ledger_form").on('submit',(function(e) {
e.preventDefault();
var data = {};
data.group_ledger_name = $('#group_ledger_name').val();
data.group_ledger_type = $('#group_ledger_type').val();
$('#loading').show();
$.ajax({
url: "/group-ledger",
type: "POST",
data: data,
dataType: 'json',
cache: false,
processData:true,
success: function(data)
{
if( data.status == '500' ) {
console.log('error occured');
} else {
$('#loading').hide();
}
}
});
}));
});
group_ledger.js
var express = require('express');
var router = express.Router();
var db = require('./../db');
var chart_func = require('./../chart-of-accounts');
router.post('/', function(req, res, next) {
var group_ledger_name = req.body.group_ledger_name;
var group_ledger_type = req.body.group_ledger_type;
chart_func.allChartsByAccountName(group_ledger_name).then(function(pre_rows){
for (var i = 0; i < pre_rows.length; i++) {
pre_account_name = pre_rows[i]['account_name'];
}
});
console.log(pre_account_name);
});
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 mysql = require('mysql');
var db = require('./db');
var routes = require('./routes/index');
var chart_of_accounts = require('./routes/chart_of_accounts');
var group_ledger = require('./routes/group_ledger');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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('/chart-of-accounts', chart_of_accounts);
app.use('/group-ledger', group_ledger);
// 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;
I have a Experss.js framework and Node.js with a request to MS SQL database on the server side.
I want to get a data(in JSON or array) from server and send to Cliend side.
I don't understand how can I write routers for another server on the Client side.
server.js
npm start
http://localhost:5000/
Code:
var sql = require("mssql");
var express = require('express');
var app = express();
var http = require('http')
var query = "SELECT AVG([sta_waittime]) AS Spalte FROM [DialogMaster_TEST].[dwh].[anruf_stat] WHERE CONVERT(DATE,sta_timestamp) = CONVERT(DATE,CONVERT(DATE,'2016-08-01')) ";
app.get('/', function (req, res) {
sql.connect("mssql://log:pas#db/TEST").then(function() {
// Query
new sql.Request().query(query).then(function(recordset) {
var a = [];
a.push(recordset[0].Spalte);
res.send(a); // **number**
}).catch(function(err) {
// ... query error checks
});
}).catch(function(err) {
// ... connect error checks
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Server site in Browser:
My app.js file.
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(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('/users', users);
//app.get('/');
// 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;
You need only 1 server(REST server). Just use node.js server.
Read it:
REST
When a user logs in a session is created for him, but if he were to go to another computer and login a 2nd session would be created for his account. I would like to make it so that a user could not have more then one valid session. Is there anyway to store sessions in redis by user.steamId so that his first session becomes invalid?
Any help would be great thanks!
app.js
var express = require('express'),
http = require('http');
var app = express();
var cookie = require('cookie');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var redis = require('redis');
var client = redis.createClient();
var session = require('express-session');
var redisStore = require('connect-redis')(session);
io.set('transports', ['websocket']);
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
const fs = require('fs');
require('./config/passport')(passport);
var sessionMiddleware = session({
store:new redisStore({host:'localhost',port:6379,client:client}),
secret:'secretTextchange',
saveUninitialized:false,
resave:false
});
// 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(sessionMiddleware);
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
require('./routes/routes')(app,passport,client);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
io.use(function(socket, next) {
sessionMiddleware(socket.request, {}, next);
});
io.sockets.on('connection', function (socket) {
console.log("verified");
socket.on('message',function(msg){
io.sockets.emit('rmessage', {
name:socket.request.session.passport.user.name,
avatarUrl:socket.request.session.passport.user.avatarUrl,
message:msg
});
});
});
// 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: {}
});
});
server.listen(3000);
module.exports = app;
passport.js
var OpenIDStrategy = require('passport-openid').Strategy;
var auth = require('./auth');
var steam = require('./steam');
var s = new steam({
apiKey: auth.Steam.apiKey,
format:'json'
})
module.exports = function(passport){
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null,user);
});
var SteamStrategy = new OpenIDStrategy({
// OpenID provider configuration
providerURL: auth.Steam.providerUrl,
stateless: auth.Steam.stateless,
// How the OpenID provider should return the client to us
returnURL: auth.Steam.returnUrl,
realm: auth.Steam.realm,
},
function(identifier, done) {
process.nextTick(function () {
console.log("passport-"+identifier);
s.getPlayerSummaries({
steamids:identifier.match(/\d+$/)[0],
callback:function(err,data){
var user = {
steamid:identifier.match(/\d+$/)[0],
avatarUrl: data.response.players[0].avatar,
name:data.response.players[0].personaname
};
return done(null, user);
}
});
// In case of an error, we invoke done(err).
// If we cannot find or don't like the login attempt, we invoke
// done(null, false).
// If everything went fine, we invoke done(null, user).
});
});
passport.use(SteamStrategy);
}
routes.js
module.exports = function(app,passport,client){
app.get('/', function (req,res) {
res.render('index.ejs',{
user: req.user,
title:"yo"});
});
app.get('/auth',passport.authenticate('openid'));
app.get('/auth/return',passport.authenticate('openid'),function(req,res){
if (req.user) {
res.redirect('/');
} else {
res.redirect('/');
}
});
}
Could you use this: https://www.npmjs.com/package/redis-sessions ?
There's a method called soid which gets all sessions of a single id. You could query user's id as they log in. Then get all the sessions from that id. If soid returns empty you can safely assume the user had no sessions. If it returns with things inside it, then the user has sessions.
This is my best attempt right now.
Good luck.
I am new to NodeJS and ExpressJS. I am following this tutorial http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ for creating and connecting mongodb with nodejs. Everything works perfectly(DB data inserting through command line,package.json config) except db connection, it throws undefined error.
var monk = require('monk');
var db = monk('localhost:27017/deno');
I check this in console like this console.log(db) it shows 'undefined' in index.js
My app.js 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');
// New Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Fujitsu');
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(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')));
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
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;
routes/index.js is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/************ Customized starts Here **********/
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
console.log(db);
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
/******** Customized - Ends here ***********/
module.exports = router;
Please anyone of you tell me the solution because now I'm struggling with this.
Thanks In Advance.