I'm newby to Node.js and back-end development. I'm trying to create web api for my mobile app on OPENSHIFT server. But I'm living problems. I'm trying to connect to DB on server.js in order to set the routings(http requests) I need. Whereas, somehow I can't define my DB in server.js. I can connect in any other file, I tried, but when I try to connect throughserver.js` I get error - whole app crashes on server. I'll try to explain with code examples.
Here is my server.js
#!/bin/env node
// OpenShift sample Node application
var express = require('express');
var fs = require('fs');
var db = require("./db_connection");//when I delete this line, there is not any error.
/**
* Define the sample application.
*/
var SampleApp = function() {
// Scope.
var self = this;
/* ================================================================ */
/* Helper functions. */
/* ================================================================ */
/**
* Set up server IP address and port # using env variables/defaults.
*/
self.setupVariables = function() {
// Set the environment variables we need.
self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
self.port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
if (typeof self.ipaddress === "undefined") {
// Log errors on OpenShift but continue w/ 127.0.0.1 - this
// allows us to run/test the app locally.
console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
self.ipaddress = "127.0.0.1";
};
};
/**
* Populate the cache.
*/
self.populateCache = function() {
if (typeof self.zcache === "undefined") {
self.zcache = { 'index.html': '' };
}
// Local cache for static content.
self.zcache['index.html'] = fs.readFileSync('./index.html');
};
/**
* Retrieve entry (content) from cache.
* #param {string} key Key identifying content to retrieve from cache.
*/
self.cache_get = function(key) { return self.zcache[key]; };
/**
* terminator === the termination handler
* Terminate server on receipt of the specified signal.
* #param {string} sig Signal to terminate on.
*/
self.terminator = function(sig){
if (typeof sig === "string") {
console.log('%s: Received %s - terminating sample app ...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()) );
};
/**
* Setup termination handlers (for exit and a list of signals).
*/
self.setupTerminationHandlers = function(){
// Process on exit and signals.
process.on('exit', function() { self.terminator(); });
// Removed 'SIGPIPE' from the list - bugz 852598.
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function(element, index, array) {
process.on(element, function() { self.terminator(element); });
});
};
/* ================================================================ */
/* App server functions (main app logic here). */
/* ================================================================ */
/**
* Create the routing table entries + handlers for the application.
*/
self.createRoutes = function() {
self.routes = { };
self.routes['/asciimo'] = function(req, res) {
var link = "http://i.imgur.com/kmbjB.png";
res.send("<html><body><img src='" + link + "'></body></html>");
};
self.routes['/'] = function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.send(self.cache_get('index.html') );
};
self.routes['/All'] = function(req, res) {
db.query("select * from users",function(err,result){
if(err)
res.json(err);
else
res.json(result);
})
};
};
/**
* Initialize the server (express) and create the routes and register
* the handlers.
*/
self.initializeServer = function() {
self.createRoutes();
self.app = express.createServer();
// Add handlers for the app (from the routes).
for (var r in self.routes) {
self.app.get(r, self.routes[r]);
}
};
/**
* Initializes the sample application.
*/
self.initialize = function() {
self.setupVariables();
self.populateCache();
self.setupTerminationHandlers();
// Create the express server and routes.
self.initializeServer();
};
/**
* Start the server (starts up the sample application).
*/
self.start = function() {
// Start the app on the specific interface (and port).
self.app.listen(self.port, self.ipaddress, function() {
console.log('%s: Node server started on %s:%d ...',
Date(Date.now() ), self.ipaddress, self.port);
});
};
}; /* Sample Application. */
/**
* main(): Main code.
*/
var zapp = new SampleApp();
zapp.initialize();
zapp.start();
And here is my db_connection.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "127.0.0.1",
port: "3307",
user: "adminm*****",
password: "zLj7Sh***",
database: "***db"
});
con.connect(function(err) {
if (err) {
throw err;
console.log("COULD NOT CONNECT!!!");
}
});
module.exports = con;
And here is the error I face
So, Can you help me, please? Why I can't declare any file on server.js?
Related
reload/reload.js route is not working
I'm using express-generator app code template to create my node applications
I also followed github issues information for this package
https://github.com/alallier/reload/issues/56#issuecomment-288393265
In this comment he said to create a custom route to listen for this file
app.get('/reloader', (req, res) => {
res.type('text/javascript')
res.sendFile(require.resolve('reload/lib/reload-client'))
});
But, when i tried this reload is not working and in console an error exception occurring:
Uncaught DOMException: Failed to construct 'WebSocket': The URL's
scheme must be either 'ws' or 'wss'. 'http' is not allowed.
at new WrappedWebSocket (:164:21)
Here is my code (bin/www)
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var reload = require('reload');
var debug = require('debug')('node1:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
reload(app); // here i'm using reload module
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
I resolved this issue by using reload(app) in ./app.js instead of ./bin/www
It is working fine in app.js file (even if i change the location of this statement) but, in ./bin/www file it is not working.
Code (./app.js):
var express = require('express');
var path = require('path');
var reload = require('reload');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressHandlebars = require('express-handlebars');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
reload(app); // Init Reload module
Here is the guide I'm basing my code off of: https://github.com/elad/node-cluster-socket.io
Although 9 threads are started, only one is in use at a time, and it's always the same thread that gets used. Their code works fine, but I've modified it to work with my program, and that's where I'm having issues.
manager.js:
var express = require('express'),
cluster = require('cluster'),
net = require('net'),
sio = require('socket.io'),
sio_redis = require('socket.io-redis');
var port = 3000,
num_processes = require('os').cpus().length;
if (cluster.isMaster) {
// This stores our workers. We need to keep them to be able to reference
// them based on source IP address. It's also useful for auto-restart,
// for example.
var workers = [];
// Helper function for spawning worker at index 'i'.
var spawn = function(i) {
workers[i] = cluster.fork();
// Optional: Restart worker on exit
workers[i].on('exit', function(code, signal) {
console.log('respawning worker', i);
spawn(i);
});
};
// Spawn workers.
for (var i = 0; i < num_processes; i++) {
spawn(i);
}
// Helper function for getting a worker index based on IP address.
// This is a hot path so it should be really fast. The way it works
// is by converting the IP address to a number by removing non numeric
// characters, then compressing it to the number of slots we have.
//
// Compared against "real" hashing (from the sticky-session code) and
// "real" IP number conversion, this function is on par in terms of
// worker index distribution only much faster.
var worker_index = function(ip, len) {
var s = '';
for (var i = 0, _len = ip.length; i < _len; i++) {
if (!isNaN(ip[i])) {
s += ip[i];
}
}
return Number(s) % len;
};
// Create the outside facing server listening on our port.
var server = net.createServer({ pauseOnConnect: true }, function(connection) {
// We received a connection and need to pass it to the appropriate
// worker. Get the worker for this connection's source IP and pass
// it the connection.
var worker = workers[worker_index(connection.remoteAddress, num_processes)];
worker.send('sticky-session:connection', connection);
}).listen(port);
} else {
// Note we don't use a port here because the master listens on it for us.
var server_local = require('./server.js');
server_local.startServer(0, function(server, io) {
// Here you might use middleware, attach routes, etc.
// Don't expose our internal server to the outside.
// Tell Socket.IO to use the redis adapter. By default, the redis
// server is assumed to be on localhost:6379. You don't have to
// specify them explicitly unless you want to change them.
io.adapter(sio_redis({ host: 'localhost', port: 6379 }));
// Here you might use Socket.IO middleware for authorization etc.
// Listen to messages sent from the master. Ignore everything else.
process.on('message', function(message, connection) {
if (message !== 'sticky-session:connection') {
return;
}
// Emulate a connection event on the server by emitting the
// event with the connection the master sent us.
server.emit('connection', connection);
connection.resume();
});
});
}
server.js:
var fs = require('fs');
var satJS = require('satellite.js');
var express = require('express');
var app = new express();
var serv = require('http').Server(app);
var sio = require('socket.io');
...
exports.startServer = function(port, callback) {
updateSatelliteData(function() {
server = app.listen(port);
io = sio(server);
initalize(io);
callback(server, io);
console.log("Server started");
});
}
function initalize(io) {
//Web stuff
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
io.sockets.on('connection', function(socket) {
...
}
etc.
}
I've created an app using the express generator which all works okay but I now want to run the app with HTTPS, I've tried to configure the node server file in /bin/www to the following:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var debug = require('debug')('****:server');
var https = require('https');
var fs = require('fs');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3001');
app.set('port', port);
var options = {
path: '../app',
port: 443,
key: fs.readFileSync('/var/www/vhosts/keys/wildcard.****.com.key'),
cert: fs.readFileSync('/var/www/vhosts/keys/wildcard.****.com.crt')
}
/**
* Create HTTPS server.
*/
var server = https.createServer(options);
But I can no longer access my app when pointing it to https://
try this out:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};
// Create a service (the app object is just a callback).
var app = express();
// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);
and create a self-signed certificate. How ? follow this link http://docs.nodejitsu.com/articles/HTTP/servers/how-to-create-a-HTTPS-server
I solved this issue modifing after creation with express-generator the bin/www file and renamed it as wwws. Then in package.json I change the "source" attribute pointing the new script.
...
"scripts": {
"start": "node ./bin/wwws"
},
...
In wwws I use an https server instead of an http and then I redirect the http requests.
Here my new wwws file. I removed the http lines in the middle of www file and I added the new server section at the end.
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('phishsense:server');
var http = require('http');
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
// Add HTTPS Section
var fs = require('fs');
var https = require('https');
var http_port = normalizePort(process.env.PORT || '8080');
var https_port = process.env.PORT_HTTPS || 8443;
var options = {
key : fs.readFileSync('server.key'),
cert : fs.readFileSync('server.crt')
};
app.set("port",https_port);
/*
° Create HTTPS server.
*/
server = https.createServer(options, app).listen(https_port, function () {
console.log('Magic happens on port ' + https_port);
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(https_port);
server.on('error', onError);
server.on('listening', onListening);
// Redirect from http port to https
http.createServer(function (req, res) {
res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });
console.log("http requet, will go to >> ");
console.log("https://" + req.headers['host'].replace(http_port,https_port) + req.url );
res.end();
}).listen(http_port);
This works for me and lets the structure created by express-generator untouched.
I am trying to use an old library balloons.io as a base for a chat app, but it's quite out dated, in this particular code I am trying to figure out how to use express 4x to parse the cookie to get an sid without getting it from the req.session
Since express 4x is not using connect anymore how can I do something similar to the below but in the new express version?
/*
* Module dependencies
*/
var sio = require('socket.io')
, parseCookies = require('connect').utils.parseSignedCookies
, cookie = require('cookie')
, fs = require('fs');
/**
* Expose Sockets initialization
*/
module.exports = Sockets;
/**
* Socket.io
*
* #param {Express} app `Express` instance.
* #param {HTTPServer} server `http` server instance.
* #api public
*/
function Sockets (app, server) {
var config = app.get('config');
var client = app.get('redisClient');
var sessionStore = app.get('sessionStore');
var io = sio.listen(server);
io.set('authorization', function (hsData, accept) {
if(hsData.headers.cookie) {
var cookies = parseCookies(cookie.parse(hsData.headers.cookie), config.session.secret)
, sid = cookies['balloons'];
sessionStore.load(sid, function(err, session) {
if(err || !session) {
return accept('Error retrieving session!', false);
}
hsData.balloons = {
user: session.passport.user,
room: /\/(?:([^\/]+?))\/?$/g.exec(hsData.headers.referer)[1]
};
return accept(null, true);
});
} else {
return accept('No cookie transmitted.', false);
}
});
});
};
Not sure if this helps, but Cookie parsing in express 4.x has been extracted to the cookie-parser package. I'm not sure, but you may be able to swap out connect.util.parseSignedCookies with cookieParser.parseSignedCookies`.
That's about all I can help you with, as I haven't used socket.io much yet.
function Sockets (app, server, pub, sub, sessionStore) {
var config = app.get('config');
var secrets = require('./config/secrets');
var client = pub;
var io = sio.listen(server);
io.set('authorization', function (handshake, callback) {
if(handshake.headers.cookie) {
// pay attention here, this is how you parse, make sure you use
// cookie-parser and cookie
var cookies = cookie.parse(handshake.headers.cookie);
var sid = cookieParser.signedCookie(cookies['balloons'], secrets.sessionSecret);
// get the session data from the session store
sessionStore.load(sid, function(err, session) {
if(err || !session) {
return callback('Error retrieving session!', false);
}
// this is not storing the data into the handshake object
handshake.headers.xygaming = {
user: session.passport.user,
room: /\/(?:([^\/]+?))\/?$/g.exec(handshake.headers.referer)[1]
};
return callback(null, true);
});
} else {
return callback('No cookie transmitted.', false);
}
});
}
I'm trying to build my first node app. My app.js file is shown below. I want to access this from aother module by doing 'app = require('app')'. I then want to access app.app, app.dbConn and app.models
The problem is that when I require this module, app.models is not present on the resulting object.
var express = require('express');
var path = require('path');
var orm = require('orm');
var settings = require('./config/settings');
var mainRouter = require('./config/routes');
var environment = require('./config/environment');
var db = require('./config/db');
var auth = require('./modules/auth');
module.exports = new function(){
this.app = express();
// middlewares must be added in order - start with the basics
environment(this.app);
if (process.env.TESTING) { dbSettings = settings.dbTesting; }
else { dbSettings = settings.db; }
// add models to the request early in the middleware chain
this.dbConn = orm.connect(dbSettings, function(err){
if (err) return console.error('DB Connection error: ' + err);
else{
this.models = db.init(this.dbConn);
this.app.use(function(req,res,next){
req.models = this.models;
next();
});
passport = auth.init(this.models);
authRouter = auth.router(passport)
this.app.use('/users', authRouter);
this.app.use(mainRouter);
}
}.bind(this));
this.app.listen(settings.port);
console.log('Server started... listening on port ' + settings.port)
}
The only way to implement what I wanted was with a function that takes a callback, in the end I rewrote my code thus:
var express = require('express');
var path = require('path');
var orm = require('orm');
var settings = require('./config/settings');
var mainRouter = require('./config/routes');
var environment = require('./config/environment');
var db = require('./config/db');
var auth = require('./modules/auth');
var app;
module.exports = function(cb){
app = express();
// middlewares must be added in order - start with the basics
environment(app);
if (process.env.TESTING) { dbSettings = settings.dbTesting; }
else { dbSettings = settings.db; }
// add models to the request early in the middleware chain
dbConn = orm.connect(dbSettings, function(err){
if (err) return console.error('DB Connection error: ' + err);
else{
models = db.init(dbConn);
app.use(function(req,res,next){
req.models = models;
next();
});
passport = auth.init(this.models);
authRouter = auth.router(passport)
app.use('/users', authRouter);
app.use(mainRouter);
cb({
dbConn: dbConn,
app: app,
models: models
});
}
});
}
if (!process.env.TESTING) {
module.exports(function(server){
server.app.listen(settings.port);
console.log('Server started... listening on port ' + settings.port)
});
}
app.models is defined only once database connection is completed: you cannot use it right away after requiring the module. You should provide an entry point that accepts a function to call once the connection is ready and call this function inside the orm.connect callback.
Even the "server started" message is a bit misleading as it's shown before the server can actually do anything because the function passed to orm.connect has not been called yet.
app.models is never defined so it is never available.
Instead, try
app.set('models', db.init(this.dbConn);