Having issues with app.configure:
debugger;
var appSettings = require('./server/config/settings/MainAppSettings.js');
// ====== DB ==============
//var sqlImport = require('./server/dbConnectors/MYSQL/MYSQLMainConn.js');
//var dbConnection = new sqlImport.sqlConn();
var dbConnection = null;
// ====== setup basic server ==============
var root = __dirname;
var express = require('express');
var app = express();
app.configure(function () {
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.errorHandler({dumbExceptions:true, showStack:true}));
});
// ====== SSL ==============
var https = require('https');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync(appSettings.key1.key),
cert: fs.readFileSync(appSettings.key1.cert)
};
// ====== Routes ==============
//handle get requests
var errors = require('./server/errors/errors.js').errors;
require('./server/config/routes/routes.js')(app, dbConnection, errors);
//keep server from crashing by catching all exceptions not caught before
process.on('uncaughtException', function(err) {
console.log(err);
});
//launch http server
app.listen(appSettings.ports.http);
console.log('Express http server listening on port %d in %s mode',appSettings.ports.http, app.settings.env);
//launch https server
https.createServer(options, app).listen(appSettings.ports.https, function(){
console.log('Express https server listening on port %d in %s mode',appSettings.ports.https, app.settings.env);
});
module.exports = app;
Seems like you are using Express 4.0 in which configure was removed.
See http://expressjs.com/guide/migrating-4.html#other-changes
Related
I recently attempted to install an SSL certificate to my server. The certificate files (privkey.pem, fullchain.pem) are in the root directory of the application. When I run the following code:
var express = require('express');
var app = express();
var helmet = require('helmet');
var db = require('./server/database.js');
var fs = require('fs');
var ssl = require('ssl-root-cas');
'use strict';
var rootCas = require('ssl-root-cas/latest').create();
// default for all https requests
// (whether using https directly, request, or another module)
require('https').globalAgent.options.ca = rootCas;
app.use(helmet());
var options = {
key : fs.readFileSync('privkey.pem', 'ascii'),
cert : fs.readFileSync('fullchain.pem', 'ascii')
}
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.use('/public', express.static(__dirname + '/public'));
var serv = require('https').createServer(options, app);
The server runs with no errors. The "Server is listening on port 80" Confirmation I added shows, and the certificate appears to not cause any direct issues. However when I attempt to connect to the domain(using https://) Chrome responds with ERR_CONNECTION_REFUSED. When connecting to the domain via http, Chrome responds with the same message. I am using SocketIO, which is initialized later in the code, I have not found any connection between my issue and SocketIO's functions. What is causing the inability to connect?
The https request is sent over port 443 rather than 80. The following code worked without issues:
var express = require('express');
var app = express();
var helmet = require('helmet');
var db = require('./server/database.js');
var fs = require('fs');
var ssl = require('ssl-root-cas');
'use strict';
var rootCas = require('ssl-root-cas/latest').create();
// default for all https requests
// (whether using https directly, request, or another module)
require('https').globalAgent.options.ca = rootCas;
app.use(helmet());
var options = {
key : fs.readFileSync('privkey.pem', 'ascii'),
cert : fs.readFileSync('fullchain.pem', 'ascii')
}
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.use('/public', express.static(__dirname + '/public'));
var serv = require('https').createServer(options, app);
//var serv = require('https').Server(app); //DEBUG ONLY
i am trying to get my chat app in node.js/socket.io to work on SSL (https), i am now at the moment i dont get errors when i startup the server but i cant connect anymore.
I googled and tried so much examples but i cant get it to work.
This was my old code (this works in http)
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
This is my changed code:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('cert.key'),
cert: fs.readFileSync('cert.crt')
};
var express = require('express')
, app = express();
var server = https.createServer(options);
var io = require('socket.io').listen(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
This is how I created the https server on node. Try it once it is working fine for me .
var port = "80";
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app);
server.listen(port);
var fs = require('fs');
var net = require('net');
var tls = require('tls');
var sslOptions = {
key: fs.readFileSync('public/server.key'),
cert: fs.readFileSync('public/server.crt')
};
tls.createServer(sslOptions, function (cleartextStream) {
var cleartextRequest = net.connect({
port: port, //your port
host: serverStr // your server address
}, function () {
cleartextStream.pipe(cleartextRequest);
cleartextRequest.pipe(cleartextStream);
});
}).listen(443);
I'm using express.js server-side and I followed the socket.io setup guide. Unfortunately the socket connection is never successful, and I receive an unruly amount of GET requests that look like this:
Here's my setup:
CLIENT - index.html
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
<script>
// var socket = io.connect('http://localhost');
var socket = io.connect('http://localhost:9000/');
socket.on('connected', function (serverData) {
console.log(serverData);
});
</script>
SERVER - /io/index.js
'use strict';
var socketio = require('socket.io');
var io = null;
module.exports = function(server) {
if (io) return io;
io = socketio(server);
io.on('connection', function(socket) {
console.log('Sockets connected!');
socket.emit('connected', 'Sockets connected!')
})
return io;
};
SERVER - app.js
'use strict';
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
console.error('MongoDB connection error: ' + err);
process.exit(-1);
});
// Populate databases with sample data
if (config.seedDB) { require('./config/seed'); }
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Setup sockets
require('./io')(server);
// Start server
function startServer() {
server.listen(config.port, config.ip, function() {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
}
setImmediate(startServer);
// Expose app
exports = module.exports = {
app: app,
server: server
}
This is tipically what happen, when client does not reach the server.
The client try again and again . . .
For that you have to check your config server-side, checking the port and the path is often the first things you should check.
In your case, maybe you should check this part :
//require('./io')(server); typo error ??
require('./io/index.js')(server);
More further you don't seem to give the good part :
( maybe depending on version you use)
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Setup sockets
require('./io')(server);
I think it should be :
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Setup sockets
//require('./io')(server); |O----------------------------------|
require('./io/index.js')(app);//<---we pass app as argument----|
I hope this will help you.
I'm trying to use simplewebrtc in my app, I already have a simple nodejs server with express web framework. But to use simpleWebrtc we have to install signal master. I'm looking at the source code for the server.js file in the signal master package but I can't figure out how to combine this server.js with my already existing app.js file. This is basically my app.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mongoose = require('mongoose');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
console.log("connected to index");
});
and this is server.js of signalMaster
/*global console*/
var yetify = require('yetify'),
config = require('getconfig'),
uuid = require('node-uuid'),
crypto = require('crypto'),
fs = require('fs'),
port = parseInt(process.env.PORT || config.server.port, 10),
server_handler = function (req, res) {
res.writeHead(404);
res.end();
},
server = null;
// Create an http(s) server instance to that socket.io can listen to
if (config.server.secure) {
server = require('https').Server({
key: fs.readFileSync(config.server.key),
cert: fs.readFileSync(config.server.cert),
passphrase: config.server.password
}, server_handler);
} else {
server = require('http').Server(server_handler);
}
server.listen(port);
var io = require('socket.io').listen(server);
if (config.logLevel) {
// https://github.com/Automattic/socket.io/wiki/Configuring-Socket.IO
io.set('log level', config.logLevel);
}
etc, etc you can look at the rest by downloading the zip. I thought it would be just replacing server with http, but the server=null doesn't really make sense. All the dependencies are in the directory of the signalMaster unzipped file. I was reading about signalMaster here.
You will need something like this
var os = require('os');
var static = require('node-static');
var http = require('http');
var socketIO = require('socket.io');
var fileServer = new(static.Server)();
var app = http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(2013);
var io = socketIO.listen(app);
io.sockets.on('connection', function (socket){
...
socket.on('join', function (message) {
...
}
...
}
i hope this help u
Can I create an Express server listening on both HTTP and HTTPS, with the same routes and the same middlewares?
Currently I do this with Express on HTTP, with stunnel tunneling HTTPS to Express, but I prefer a pure Node solution.
I can do it with this code, but using the handle method that is marked as private:
var express = require( 'express' )
, https = require("https")
, fs = require( 'fs' );
var app = express.createServer();
// init routes and middlewares
app.listen( 80 );
var privateKey = fs.readFileSync( 'privatekey.pem' ).toString();
var certificate = fs.readFileSync( 'certificate.pem' ).toString();
var options = {key: privateKey, cert: certificate};
https.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen( 443 );
To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following
Create an express app:
var express = require('express');
var app = express();
The app returned by express() is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.
You can do so as follows:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem'),
ca: fs.readFileSync('/path/to/ca.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
For complete detail see the doc
As a possible update to this question, you might want to check out the changes here for express 3. The change document says:
The return value of express() is a JavaScript Function,
encapsulating everything that makes an Express app tick. This means
you can easily setup HTTP and HTTPS versions of your application by
passing it to node's http.createServer() and https.createServer():
In Express 3, express.createServer() is now express()
Here is a complete example for express 3:
var fs = require('fs')
, https = require('https')
, http = require('http')
, express = require('express')
, keys_dir = 'keys/'
, server_options = {
key : fs.readFileSync(keys_dir + 'privatekey.pem'),
ca : fs.readFileSync(keys_dir + 'certauthority.pem'),
cert : fs.readFileSync(keys_dir + 'certificate.pem')
}
, app = express();
app.configure(function(){
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session( { secret: '' } ));
app.use(app.router);
});
app.configure('development',function(){
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({dumpExceptions: true, showStack:true}));
app.set('view options', { pretty: true });
});
app.get('/', function(req, res){
res.send('Hello World!');
});
https.createServer(server_options,app).listen(7000);
http.createServer(app).listen(8000);
You can share the implementation via something like:
var register = function (app) {
// config middleware
app.configure({
});
// config routes
app.get(...);
};
var http = express.createServer();
register(http);
http.listen(80);
var https = express.createServer({ key: /* https properties */ });
register(https);
https.listen(443);
You can use express and https in same port.
this works for me.
const express=require('express');
const app=express();
const cors=require('cors');
const path=require("path");
const routes=require('./routes/api');
const routerComplain=require('./routes/api');
const routerstores=require('./routes/api');
const routerstock=require('./routes/api');
const routerreport=require('./routes/api');
const routeritem=require('./routes/api');
const bodyParser=require('body-parser');
const routerRegister=require('./routes/api');
const mongoose=require('mongoose');
var server = require('http').Server(app);
var io = require('socket.io')(server);
require("dotenv").config();
mongoose.connect('mongodb://#################',{ useNewUrlParser: true },(err)=>{
if(!err){
console.log('db connected')
}else{
console.log('error in db')
}
});
mongoose.Promise = global.Promise;
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(cors({credentials: true, origin:'http://localhost:3000'}));
app.use(express.static(path.join(__dirname, "client", "build")))
app.use('/reg',routes);
app.use('/complain',routerComplain);
app.use('/register',routerRegister);
app.use('/stores',routerstores);
app.use('/reports',routerreport);
app.use('/stock',routerstock);
app.use('/items',routeritem);
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
})
const port = process.env.port||4000;
server.listen(port,function(){
console.log('now listening for request');
});
If you want to use the traditional two ports, one of the above solutions probably works, but using httpolyglot, you can really easily have http and https on the same port with the same middlewares.
https://github.com/mscdex/httpolyglot
Here's some skeleton code that worked for me:
var express = require('express');
var fs = require('fs');
var httpolyglot = require('httpolyglot');
var app = express();
const options = {
key: fs.readFileSync("/etc/ssl/certs/key"),
cert: fs.readFileSync("/etc/ssl/certs/cer.cer")
};
httpolyglot.createServer(options, app).listen(port);
and if you want http -> https forwarding, you can just add this middleware function before the createServer() call:
app.use(function(req, res, next) {
if (!req.secure ) {
res.redirect (301, 'https://' + req.hostname + ':port' + req.originalUrl);
}
next();
});
This can be set up on a custom port
Similar post
Can I configure expressjs to serve some pages over http and others over https?
Be aware that express now support creating Https servers with:
var app = require('express').createServer({ key: ... });