I create web applications using NodeJS and ExpressJS, I use the https server. I would like all the devices connected to the same network not to enter the ip address of the localhost, and instead could enter, for example: https://SmartphoneMonitoring.com and would be redirected to the localhost
server script:
var connections = [];
var express = require('express');
var bodyParser = require('body-parser')
var expressValidator = require('express-validator');
var hbs = require('hbs'); //handlebars
var session = require('express-session');
var cookieParser = require('cookie-parser');
var fs = require('fs');
var routes = require('./routes/router');
var https = require('https');
var path = require('path');
var mysql = require('mysql');
var dns = require('dns');
dns.resolve4('www.google.com', function (err, addresses) {
if (err) throw err;
console.log('addresses: ' + JSON.stringify(addresses));
addresses.forEach(function (a) {
dns.reverse(a, function (err, domains) {
if (err) {
console.log('reverse for ' + a + ' failed: ' + err.message);
} else {
console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
}
});
});
});
var databasePort = 3306;
var dataBaseName = 'BazaDanych';
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
port: databasePort,
database: dataBaseName
});
setTimeout(function(){connectToDB()},1000);
function connectToDB(){
db.connect((err) =>{
if(err){
console.log(err);
} else {
console.log('Połączono z bazą danych na porcie: ' + databasePort)
}
});
};
var app = express();
const httpsOptions = {
cert: fs.readFileSync(path.join(__dirname, 'ssl', 'server.crt')),
key: fs.readFileSync(path.join(__dirname, 'ssl', 'server.key'))
};
var server = https.createServer(httpsOptions, app);
var io = require('socket.io', { rememberTransport: false, transports: ['WebSocket', 'Flash Socket', 'AJAX long-polling'] }).listen(server);
app.set('views', (__dirname, 'views'));
app.set('view engine', '.hbs');
hbs.registerHelper('json', function(obj){
return new hbs.SafeString(JSON.stringify(obj));
})
//Partials
const partialsDir = __dirname + '/views/partials';
const filenames = fs.readdirSync(partialsDir);
filenames.forEach(function (filename) {
const matches = /^([^.]+).hbs$/.exec(filename);
if (!matches) {
return;
}
const name = matches[1];
const template = fs.readFileSync(partialsDir + '/' + filename, 'utf8');
hbs.registerPartial(name, template);
});
//Partials
hbs.registerHelper('ifequal',function(a, b,options)
{
if (a==b){
return options.fn(this);
} else {
return options.inverse(this);
}
});
var serverPort = 3030;
server.listen(serverPort, function(){
console.log("Połączono z serwerem na porcie: " + serverPort);
})
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use(cookieParser());
app.use(session({
key: 'user_sid',
secret: 'fsdfdsfsdfsdfsdfsdf',
resave: false,
saveUninitialized: false
}));
app.use('/', routes);
I tried to get the effect using DNS but it did not bring the expected results.
Related
The closest I've been able to get is it will have the client download them. It will download the correct ejs files.
It's driving me crazy because I feel like it should work but it will not. If I put html files in there they serve just fine. It's a little messy because I've been trying all sorts of things.
var application_root = __dirname;
var express = require('express');
var vhost = require( 'vhost' );
var https = require('https');
var http = require('http');
var fs = require('fs');
var path = require("path");
var forceSSL = require('express-force-ssl');
//do something
var app = express();
var credentials = {};
var config = require('./config.json')[process.env.NODE_ENV || 'dev'];
//Use ejs?
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
//Ensure all are going to www.
app.all(/.*/, function(req, res, next) {
var host = req.header("host");
if (host.match(/^www\..*/i)) {
next();
} else {
res.redirect(301, "http://www." + host);
}
});
//Use the virtual hosts
app.use(vhost('*.seq.agency',express.static(path.join(__dirname + '/seq.agency'), {
extensions: ['ejs'],
index: 'index.ejs'
})));
app.get('/', function (req, res) {
res.send('vhosts didn\'t catch this!')
});
var httpServer = http.createServer(app);
if(config.name == "prod"){
/*var options = {
key: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/fullchain.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/chain.pem')
}*/
console.log('starting on 443');
//var httpsServer = https.createServer(options, app);
//httpsServer.listen(443);
//httpServer.listen(80);
//app.use(forceSSL);
}
console.log('['+config.name+'] starting on port',config.port);
httpServer.listen(config.port);
The issue is that you are considering that static files are rendered. Static file as the name suggest is static and there is no dynamic behavior and template rendering needed for the same
That is why below code cannot work
app.use(vhost('*.seq.agency',express.static(path.join(__dirname + '/seq.agency'), {
extensions: ['ejs'],
index: 'index.ejs'
})));
As you are asking it to serve files as it is with no processing. So I modified your code a bit to show you an example how you could work something out on this
var application_root = __dirname;
var express = require('express');
var vhost = require( 'vhost' );
var https = require('https');
var http = require('http');
var fs = require('fs');
var path = require("path");
var forceSSL = require('express-force-ssl');
//do something
var app = express();
var credentials = {};
var config = require('./config.json')[process.env.NODE_ENV || 'dev'];
//Use ejs?
ejs = require("ejs");
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);
app.engine('ejs', ejs.renderFile);
//Ensure all are going to www.
app.all(/.*/, function(req, res, next) {
var host = req.header("host");
if (host.match(/^www\..*/i)) {
next();
} else {
res.redirect(301, "http://www." + host);
}
});
//Use the virtual hosts
app.use(vhost('*.seq.agency',function (req, res, next)
{
const reqPath = req.path;
const paths =
[
reqPath + ".html",
reqPath + "index.html",
reqPath
]
for (file of paths) {
try {
let checkPath = path.join(__dirname,"seq.agency", file);
if (!fs.existsSync(checkPath))
continue;
let stat = fs.statSync(checkPath);
if (stat && stat.isFile())
{
res.render(checkPath);
return;
}
} finally {
}
}
console.log(file);
}));
app.get('/', function (req, res) {
res.send('vhosts didn\'t catch this!')
});
var httpServer = http.createServer(app);
if(config.name == "prod"){
/*var options = {
key: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/fullchain.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/chain.pem')
}*/
console.log('starting on 443');
//var httpsServer = https.createServer(options, app);
//httpsServer.listen(443);
//httpServer.listen(80);
//app.use(forceSSL);
}
console.log('['+config.name+'] starting on port',config.port);
httpServer.listen(config.port);
So the key is that we check a path in below order
reqPath + ".html",
reqPath + "index.html",
reqPath
And then if it exists then we render that in response. This is no way a production use code as it allows you to directory traversal attack, but this is to give you an idea of what you are doing wrong and how you should handle it
I have a nodejs app running on Heroku. Here is the server.js file
var express = require('express')
, cors = require('cors')
, app = express();
var http = require('http').Server(app);
var io = require("socket.io").listen(http);
app.use(cors());
require('./modules/routes.js')(app,io);
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is my routes.js
"use strict";
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var time = require('express-timestamp');
var Promise = require('promise');
var momentjs = require('moment');
var _ = require('lodash');
var method = routes.prototype;
function routes(app, io) {
app.use(time.init);
app.use(cookieParser());
app.use(session({ secret: 'asdo8rter65edfgfd53wet34634632y4bluaq', resave: true, saveUninitialized: true }));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(bodyParser.json());
app.post('/testHeroku', function(req, res) {
console.log(req);
res.write(JSON.stringify({
process: "success"
}));
res.end();
});
}
method.getroutes = function() {
return this;
}
module.exports = routes;
I'm trying to access /testHeroku from an ionic app running in android emulator.
Ionic code:
vm.testHeroku = function(){
console.log('testing heroku');
var testdata = {
url: config.baseURL + 'testHeroku',
dataServer: {
serverTaskRequest: 'getUADSF'
}
}
runajax.runajax_function(testdata, function (testdataResponse) {
if (testdataResponse.process == 'success') {
alert(testdataResponse.process);
}
});
};
Here goes my config.baseURL = abcd-1234.herokuapp.com (This is example for the heroku app url)
I don't receive any return form the http call.
Code for run_ajax service
.service('runajax', ['$http', function ($http) {
this.runajax_function = function (request, callback) {
var url = request.url;
var dataServer = request.dataServer;
// console.log('runajax function called -> ' + url);
// console.log(dataServer);
$http.post(url, dataServer).success(function (data, status, headers, config) {
callback(data);
})
.error(function () {
callback(status);
});
}
}])
I got it working. There was an error with app.set('port', process.env.PORT || 5000); I changed it to var port = process.env.PORT || 8080;
I want to establish https request to my api and i have written following lines of code in NodeJS function:
function getUsers() {
/**
* HOW TO Make an HTTP Call - GET
*/
// options for GET
var optionsget = {
host: 'localhost', // here only the domain name
// (no http/https !)
port: 3000,
path: '/api/users', // the rest of the url with parameters if needed
method: 'GET' // do GET
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
// do the GET request
var reqGet = https.request(optionsget, function (res) {
console.log('Requested');
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function (d) {
console.info('GET result:\n');
process.stdout.write(d);
console.info('\n\nCall completed');
});
});
reqGet.end();
reqGet.on('error', function (e) {
console.error('Last error:' + e);
});
}
Server side 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 mysql = require("mysql");
var md5 = require('MD5');
var rest = require("./REST.js");
var index = 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', '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')));
function REST() {
var self = this;
self.connectMysql();
}
REST.prototype.connectMysql = function () {
var self = this;
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: 'root',
database: 'oes_api',
debug: false
});
pool.getConnection(function (err, connection) {
if (err) {
self.stop(err);
} else {
self.configureExpress(connection);
}
});
};
REST.prototype.configureExpress = function (connection) {
var self = this;
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var router = express.Router();
app.use('/api', router);
app.use('/', index);
app.use('/users', users);
var rest_router = new rest(router, connection, md5);
self.startServer();
};
REST.prototype.startServer = function () {
app.listen(3000, function () {
console.log("All right! I am alive at Port 3000.");
});
};
REST.prototype.stop = function (err) {
console.log("ISSUE WITH MYSQL \n" + err);
process.exit(1);
};
new REST();
But https connection is not establishing saying Last error:Error: socket hang up.
Could you please help me out to get ride out from this error.
It looks like you can create your server using https. Take a look at this page in the Node Documentation for doing so.
Example
const https = require('https');
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
I'm connecting Socket in my App but the configuration is mismatched because of which socket is not connecting. What could be the problem? I'm referring to "Mastering Web Application Development with Express" for structuring
app.js
var express = require('express');
var app = express();
var morgan = require('morgan'); //HTTP request logger middleware for node.js
var flash = require('connect-flash');
var multiparty = require('connect-multiparty');
var cookieParser = require('cookie-parser');
var cookieSession = require('express-session');
var bodyParser = require('body-parser'); //Node.js body parsing middleware
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
var config = require('./config.js');
var passport = require('passport');
var fs = require('fs');
var sessionStore = new cookieSession.MemoryStore();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
morgan.token('id', function getId(req) {return req.id })
var accessLogStream = fs.createWriteStream(__dirname + '/log/systemAccessWithToken.log', {flags: 'a'})
app.use(assignId)
app.use(morgan(':id :method :url :response-time', {stream: accessLogStream}))
function assignId(req, res, next) {
next()
}
app.use(bodyParser.json()); //middleware that only parses json
app.use(bodyParser.urlencoded({extended: true}));
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;
}
}));
app.use(cookieParser());
app.use(cookieSession({
store: sessionStore,
secret: config.sessionSecret,
cookie: {maxAge: config.sessionMaxAge}
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
if (app.get('env') === 'development') {
app.use(errorHandler());
}
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(express.static(__dirname + '/public'));
require('./app/passport')(passport); // pass passport for configuration
var socketcon = require('./app/mainSocket.js');
socketcon.socketconfig(app, io, sessionStore, cookieParser);
require('./routes/controller.js')(app, passport); // load our routes and pass
server.listen(config.port);
mainSocket.js
var modules = require('../externalModules.js');
var dbConnection = modules.dbConnection;
var cryptography = modules.cryptography;
var onlineUsers = {};
var onlineUsersSocketid = {};
exports.socketconfig = function(app, io, sessionStore, cookieParser) {
io.set('authorization', function(data, callback) {
if (!data.headers.cookie) {
return callback('No cookie transmitted.', false);
}
cookieParser(data, {}, function(parseErr) {
if (parseErr) {
return callback('Error parsing cookies.', false);
}
var sidCookie = (data.secureCookies && data.secureCookies['myuser.sid']) || (data.signedCookies && data.signedCookies['myuser.sid']) || (data.cookies && data.cookies['myuser.sid']);
sessionStore.load(sidCookie, function(err, session) {
if (err || !session || !session.passport.user) {
callback('socket Not logged in.', false);
} else {
data.session = session;
socketSession = session;
console.log("socketSession value " + JSON.stringify(socketSession));
callback(null, true);
}
});
});
});
io.sockets.on('connection', function(socket) {
console.log("socket connected");
console.log("socket.id " + socket.id);
socket.encryptedUserid = socketSession.passport.user.userId;
var devicetype = "web";
var secUserSalt = socketSession.passport.user.salt;
socket.userid = cryptography.crypto.fnDecryption(
socket.encryptedUserid, secUserSalt);
var isMobile = socketSession.passport.user.isMobile;
var devicetype = "web";
if (isMobile) {
devicetype = "mobile";
}
socket.on('user:join', function() {
//==============================develpoment(Aug21)====================
if (socket.userid in onlineUsersSocketid) {
onlineUsersSocketid[socket.userid].sockets_ids
.push(socket.id);
onlineUsersSocketid[socket.userid].devicetype
.push(devicetype);
} else {
onlineUsersSocketid[socket.userid] = {
"sockets_ids": [socket.id], // array for all sockets id of this user
"devicetype": [devicetype]
}
}
console.log("onlineUsersSocketid " + JSON.stringify(onlineUsersSocketid));
});
socket.on('disconnect', function() {
delete onlineUsersSocketid[socket.userid];
});
});
} // end of export module
What could be the issue?
Per the socket.io docs, these are two server-side initialization sequences that should work:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
or
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
You don't have either of these.
I'm using express and socket.io and I want to share the express session between the two, with each one being on a different Node instance (localhost:3000 and localhost:8000). So far, express will create the session and the cookie created, however socket.io only picks up the 'io' cookie, not the express cookie. Can anyone show mw here my error is? I'm using express 4.x and socket.io 1.x.
Express config (localhost:3000):
var cookieParser = require('cookie-parser')
, session = require('express-session')
, bodyParser = require('body-parser')
, express = require('express')
, redis = require('redis')
, RedisStore = require('connect-redis')(session);
module.exports = function (app, passport) {
app.use(express.static('./static'))
app.use(cookieParser("thisismynewsecret"));
app.use(session({
//passport: passport,
name: 'sid',
//key: 'express.sid',
secret: 'thisismynewsecret',
saveUinitialized: true,
resave: true,
store: new RedisStore({ client: redis.createClient() }),
cookie: {
httpOnly: true,
path: '/',
secure: false
}
}));
app.use(passport.initialize());
app.use(passport.session());
// all environments
app.set('port', process.env.PORT || 3000)
app.set('views', './views')
app.set('view engine', 'jade')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(require('method-override')());
app.use( require('express-subdomain-handler')({ baseUrl: 'localhost', prefix: 'myprefix', logger: true }) );
}
});
socket.io (localhost:8000):
var fs = require('fs');
var session = require('express-session');
var cookie = require('cookie');
var cookieParser = require('cookie-parser');
var sessionStore = require('connect-redis')(session);
var server = require('http').Server(function(req, res) {
fs.readFile(__dirname + '/views/JAMinit.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
}).listen(8000);
var io = require('socket.io')(server);
io.use(function(socket, next) {
var data = socket.handshake || socket.request;
if (data.headers.cookie) {
data.cookie = cookie.parse(cookieParser.signedCookie(data.headers.cookie, 'thisismynewsecret'));
console.log(data.cookie);
console.log('data.cookies ( %s )', JSON.stringify(data.cookie));
if (data.cookie.sid) {
data.sid = data.headers.cookie.sid;
sessionStore.get(data.headers.cookie.sid, function(err, session) {
data.session = session;
});
}
}
next();
});
Check out express.io, it combines express and socket.io and has automatic session support.