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'));
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 am working on making adjustments to teammates code and I haven't been able to understand how they have done their routing. I am attempting to have Express run a middleware script when an end-user goes to a new session of the web application.
I don't know what to test next to figure out how they have done their routing.
Main.js
// Dependencies
var http = require('http');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var busboy = require('connect-busboy');
var cors = require('cors');
var mongoose = require('mongoose');
// Configuration
var config = require('./config');
var twilio = require('twilio');
// Database
mongoose.connect(config.database);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
console.log('Connected to database');
});
var app = express();
app.set('port', process.env.PORT || 3000);
// Setup middleware
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.sessionSecret));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(busboy());
app.use(cors({
origin: true,
credentials: true
}));
app.all('/*',function(req,res){
twilio.notifyOnSession();
console.log('Message Sent');
})
var server = http.createServer(app);
var port = app.get('port');
server.listen(port);
console.log('Listening on port ' + port);
// Load server router
require('./router')(app);
/router/index.js
var path = require('path');
module.exports = function(app){
console.log('Initializing server routing');
require('./auth')(app);
require('./api')(app);
// Determine if incoming request is a static asset
var isStaticReq = function(req){
return ['/auth', '/api', '/js', '/css'].some(function(whitelist){
return req.url.substr(0, whitelist.length) === whitelist;
});
};
// Single page app routing
app.use(function(req, res, next){
if (isStaticReq(req)){
return next();
}
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
};
Your app.all('/*' is swallowing all requests before they can hit your router.
Don't do that.
I was able to resolve the issue by creating a new route with twilio.js and having the router look for the url twilio/new. Thanks all for the help.
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 am using Cloude 9 environment for developing my nodejs app. In that I have written code to connect to mongodb database. I am successfully connecting to database. But when I try to do operations on database the page becomes not responsive and hangs.
Below is the code of my server.js file
var Db = require('mongodb').Db;
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var ejs = require('ejs');
var app = express();
var helpers = require('express-helpers')
var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var db;
helpers(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () {
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// MongoDB Connection
app.use(function(req, res, next) {
next();
})
app.post('/ajax-mongo-connect', function (req, res) {
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
if(err){
console.log(err);
}else{
var db = mongoClient.db("mydb");
console.log('database connected',db);
mongoClient.close();
}
})
})
Note that from my view page I am calling action ajax-mongo-connect with POST method. To call goes to app.post('/ajax-mongo-connect'... but page becomes irresponsible and hangs.
Let me know what I am doing.
You need to return something in your /ajax-mongo-connect route, for example res.send('its working dude!'); or call the next() function.
Cheers!