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.
Related
I have the following code:
URL is "localhost:8080/ZTESTSMT"
var express = require('express');
var cors = require('cors');
const proxy = require('express-http-proxy');
var process = require('process');
var app = express();
app.use(cors())
app.set('port', (process.env.PORT || 8080));
app.use("/ZTEST123", express.static(__dirname + '/ZTEST123/webapp'));
app.use("/ZTESTSMT", express.static(__dirname + '/ZTESTSMT/webapp'));
app.use(proxy('http://localhost:8000/sap/opu/odata/sap/service1/$metadata?sap-client=001&sap-language=EN'));
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
app.all('/', function(request, response) {
});
app.listen(app.get('port'), function() {});
setTimeout(function() {
process.exit();
}, 1000000);
Now I want to use different proxy for each path.
ztest123 and ztestsmt.
I found a lot of examples but nothing worked.
I thought of something like this:
app.use("/ZTEST123", proxy('http://localhost:8000/sap/opu/odata/sap/service1/$metadata?sap-client=001&sap-language=EN'));
app.use("/ZTESTSMT", proxy('http://localhost:8000/sap/opu/odata/sap/service2/$metadata?sap-client=001&sap-language=EN'));
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 just want to capture the response error from a middleware function, it works if I write the code as follows:
var express = require('express');
var expressValidator = require('express-validator');
var app = express();
var bodyParser = require('body-parser');
var router = require('./routes');
//monk.mongoList();
app.use(bodyParser.urlencoded({extented:true}));
app.use(bodyParser.json());
app.use(expressValidator([]));
var port = process.env.PORT || 8978;
router.get('/',function(req,res,next) {
var error = Error('Article is not found');
next(error.message);
return res.send("Hello World!");
});
app.use(function(err,req,res,next) {
console.log(err + "TET");
})
app.listen(port);
but I want to separate the following code:
app.use(function(err,req,res,next) {
console.log(err + "TET");
})
and use it as follows:
app.js
var express = require('express');
var expressValidator = require('express-validator');
var app = express();
var bodyParser = require('body-parser');
var router = require('./routes');
//monk.mongoList();
app.use(bodyParser.urlencoded({extented:true}));
app.use(bodyParser.json());
app.use(expressValidator([]));
var port = process.env.PORT || 8978;
var test = require('./util/test')
app.use(test.logger);
app.use('/',router);
app.listen(port);
console.log('test node API ' + port );
util/test.js
module.exports.logger = function (err, req, res, next) {
console.log('LOGGED')
next()
}
/routes/index.js EDIT: I just edited the /routes/index.js file to make it more simple
var express = require('express');
var router = express.Router();
var url = require('url');
router.get('/api', function(req, res, next) {
var err = "this is error";
var error = Error (err)
var data = { data: "Succuss"}
if (err) {
next(error.message)
res.json({message:err})
}else {
res.json(data);
}
});
module.exports = router;
When add the above code, nothing appear in the console.
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;