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
Related
I have this code:
var express = require('express');
const proxy = require('express-http-proxy');
var process = require('process');
var app = express();
app.set('port', (process.env.PORT || 8080));
app.use('/ZTESTSMT', express.static(__dirname + '/ZTESTSMT/webapp'));
app.use('/', proxy(function(request, response) {
return 'http://localhost:8000' + request.url
}))
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
app.listen(app.get('port'));
setTimeout(function() {
process.exit();
}, 100000);
Now I want to have it like this. Dynamic paths depending on the URL.
var express = require('express');
const proxy = require('express-http-proxy');
var process = require('process');
var app = express();
app.set('port', (process.env.PORT || 8080));
app.use('$Variable', express.static(__dirname + '$Variable'));
app.use('/', proxy(function(request, response) {
return 'http://localhost:8000' + request.url
}))
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
app.listen(app.get('port'));
setTimeout(function() {
process.exit();
}, 100000);
Is this possible? I have seen the solution of Lamia but I do not use app.get How does it fit in there?
If you mean using a variable like the following,
const express = require('express');
const app = express();
let path = '/path'
app.get(path,(req,res)=>{
console.log(__dirname+path);
res.send('hello');
});
app.listen(3000)
then yes, it is possible.
I'm using Express Static node server and have the following server.js code:
var express = require('express');
var app = express();
var fs = require('fs');
var publicdir = __dirname + '/client';
app.set('port', 8080);
app.use(function(req, res, next) {
if (req.path.indexOf('.') === -1) {
var file = publicdir + req.path + '.html';
fs.exists(file, function(exists) {
if (exists)
req.url += '.html';
next();
});
} else {
next();
}
});
app.use(express.static(publicdir));
// Listen for requests
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
I'm currently trimming off the .html from the file names to clean up the URLs (eg, mysite.com/blog-article-title). The last step I'd like to do is to make it so it adds a trailing "/" to the URL, but I'm not sure how to do it. (eg, mysite.com/blog-article-title/).
Express Routing
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
app.set('port', 3001);
app.use(express.static(path.join(__dirname, 'client')));
app.get('/blog-article-title/', function(req, res) {
res.sendFile("blog-article-title.html");
})
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
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'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.
//server.js
app.use('/shelf', require('./books').middleware);
//books.js
var app = new express.Router();
app.post('/books' , function (req, res) {
console.log('here');
});
module.exports = app;
This is what i did so far; my server runs under server.js, and when i make a '/shelf/books' request, it first goes to server.js and then to the books.js file and logs 'here'. but i want to add a request handler(a different file, handler.js i.e) where i want to to validate if the post param is a number and than redirect it to books.js if it is.
app.js
var express = require('express')
, http = require('http')
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(require('./handler').middleware);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
handler.js
var express = require('express')
var books = require('./books')
var router = new express.Router();
router.get('/shelf/:book_id', function(req, res){
var onlyNumbers =req.param('book_id').match(/^\d+$/)
if (onlyNumbers){
var parsedNumber = parseInt(req.param('book_id'));
if( parsedNumber ) {
books(parsedNumber)
console.log("Parsed number is : " + parsedNumber)
res.end("Parsed number is : " + parsedNumber)
}
}
else {
console.log("not a number : " + req.param('book_id'))
res.end("not a number : " + req.param('book_id'))
}
res.end('');
})
module.exports = router;
books.js
var express = require('express')
var app = new express.Router();
module.exports = function(req, res) {
console.log("\t in books module")
};
How about this?
//handler.js
module.exports = function (req, res, next) {
req.check_result = /\d+/.test(req.body.yourfield);
};
// book.js
app.post('/books' , function (req, res) {
if(req.check_result) {
// your code
} else {
// your code
}
});
// server.js
app.use('/shelf', require('./handler'));
app.use('/shelf', require('./books').middleware);