How can i have access to my node js application everywhere? - node.js

I need some explanation. My node JS application is only accessible for me (the network). How can i have make my node js application online ? Do i necessary need to redirect the application via the port 80 ? I need to have access to my application everywhere via the port 8124. http://example.com:8124.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var i;
/**
* Gestion des requêtes HTTP des utilisateurs en leur renvoyant les fichiers du dossier 'public'
*/
app.use('/', express.static(__dirname + '/public'));
/**
* Lancement du serveur en écoutant les connexions arrivant sur le port 8124
*/
http.listen(8124, function () {
console.log('Server is listening on *:8124');
});
In the function listem, do i have to specify something specific as second parameter ? Also is it safe to let access to people with that type of url ?

I'd suggest you look into developing on Cloud9. There are no firewall issues to worry about and you can work on your project anywhere and behind any firewall.
If you insist on developing on your own network, then you may want to look into changing your hostname file. You can map example.com to map to localhost very simply.

Related

Passing a sql table created with alasql from Server (node.js) to Client (ejs)

I would be very glad to get some help on the following topic, given I didn't manage to get through it.
My objective is to gather some data on the server side (so far I'm using alasql to transform my CSV fil into a sql table), and then pass it as a parameter to the client side, to perform other sql operations on Client side (again with alasql).
So far, I suceeded in
Transforming the CSV file into a sql table thanks to alasql
Passing a parameter from the Server side to the Client Side
But I did not manage to
Pass the sql table itself from the Server side to the Client side as a parameter
My best result in trying to do so is
`input=[object Object],[object Object],...`
instead of the sql table I would expect,which gives an error
My code on the Server side is the following:
var express = require('express');
var session = require('cookie-session'); // Charge le middleware de sessions
var bodyParser = require('body-parser'); // Charge le middleware de gestion des paramètres
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var alasql=require('alasql');
var app = express();
var input=0;
alasql('SELECT * FROM CSV("public/data/output.csv",{separator:";"})',[],function(data){
input=data;
console.log(1)
});
/* On utilise les sessions */
app.use(session({secret: 'TBC'}))
/* S'il n'y a pas de todolist dans la session, on en crée une vide sous forme d'array avant la suite */
.use(function(req, res, next){
next();
})
.use(express.static(__dirname + '/public'))
/* On affiche la todolist et le formulaire */
.get('/segmentation_clients', function(req, res) {
console.log(input);
var Commercial='U.Morel';
res.render('segmentation_clients.ejs', {Commercial:'U. Morel',input:input});
})
.listen(8080);
The beginning of the JS code on the Client side (segmentation_clients.ejs):
var Commercial="<%=Commercial%>";
var input= <%=input%>;
console.log(input);
The output of the code (ok for the #Commercial parameter but not ok for the #input SQL table):
enter image description here
I would greatly appreciate your help on this topic
Thanks a lot
Stéphane
I finally got the solution:
On Server side, I replacedinput:input
with
input:JSON.stringify(input)
On Client side, I replaced var input= <%=input%>;
with
var input= <%-input%>;
The first problem was a problem of format (solved by transforming the input in a JSON format), and the second problem was about evaluating the data inside the arry with "-" instead of only reading it "=", as far as I understood
Best
Stéphane

parse-Server cloudCode with nodejs

I am using parse-server and I want to use nodejs with cloudCode as in the example below.
This is the example:
Adding nodejs to Parse
here is the example code from the link
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var ParseCloud = require('parse-cloud-express');
var Parse = ParseCloud.Parse;
var app = express();
// Host static files from public/
app.use(express.static(__dirname + '/public'));
// Define a Cloud Code function:
Parse.Cloud.define('hello', function(req, res) {
res.success('Hello from Cloud Code on Node.');
});
// Mount the Cloud Code routes on the main Express app at /webhooks/
// The cloud function above will be available at /webhooks/function_hello
app.use('/webhooks', ParseCloud.app);
// Launch the HTTP server
var port = process.env.PORT || 80;
var server = http.createServer(app);
server.listen(port, function() {
console.log('Cloud Code on Node running on port ' + port + '.');
});
console.log(process.env.PORT);
I have imported all the required modules, but still, when I run the server and try to go to the link "127.0.0.1/webhooks/function_hello" I get back Cannot GET /webhooks/function_hello
Any advise?
*OUTPUT when i run the script *
undefined
Cloud Code on Node running on port 80.
UPDATE it seems that with parse's shutdown that they have changed support status for cloudcode which affects integrating it with NodeJs
Had the same issue. GET doesn't work here. You need to make a POST request, and then you'll get {"success":"Hello from Cloud Code on Node."}
Please make sure you are running the right script with node SCRIPT_NAME
It appears your express server is set to port 5000.
See: var port = process.env.PORT || 5000;
Change your URL to http://127.0.0.1:5000/webhooks/function_hello or localhost:5000/webhooks/function_hello and it should appear
If you want to run on the default port (80) you will need to run with sudo for your script and make the following change to the code.
var port = process.env.PORT || 80;
Add a folder to your directory named public. Inside that folder place a file named index.html. Type Hello World in that file, save it. Restart your server. See if you can open http://127.0.0.1/.

Use variable subdomains for routing with wildcard

I want to create an express application that uses dynamic/variable subdomains for routing. This is what I want to do:
http://<username>.mysite.dev should forward the requests to the users/index.js
In the users/index.js I will access the username via req.subdomain[0]. It would be nice if I could also run an regular expression check on <username>.
My first approach:
I am using the node package express-subdomain to route the requests:
/* import node packages */
var express = require('express'),
subdomain = require('express-subdomain');
/* application config */
var app = express(),
port = process.env.PORT || 3000;
/* import all apps */
var users = require('./users/index.js');
/* route requests by subdomain */
app.use(subdomain('*', users));
app.get('/', function(req,res) {
/* Never get here */
res.send('Homepage');
});
/* run app on given port */
app.listen(3000, function() {
console.log('Listening on port ' + port + ' ...');
});
The problem with this approach is that the * is not working properly. It forwards all requests to my users/index.js even when there is no subdomain (http://mysite.dev). One solution for this problem would be, if I change the routing like this:
app.use(subdomain('*.users', users));
So I can access the users/index.js through http://<user>.users.mysite.dev and I can also reach the normal site, when there is no subdomain. But this approach is not really what I want - the users subdomain is too much. In addition I can not use regex.
Now, I am searching for a better solution for this problem.

Node JS express app not serving index file on Openshift. Works on local

I've done some updates to my node app, deployed to OpenShift and now it wont send the index.html file when live. I updated Express too and fixed all the errors from there...
My Directory structure is as follows:
/Site/
....server.js
....app/
........index.html/
My server looks like this:
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static('app'));
require('./server-stripe.js')(app);
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname + 'app/index.html'));
});
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || process.env.OPENSHIFT_INTERNAL_IP ||'127.0.0.1'
app.listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", server_port " + server_port )
});
It works fine on my local environment but in Production I get a 503 Service Unavailable.
Any advice would be greatly appreciated! Whits end and all that ;)
Thanks,
Matt
Edit
This is the log:
==> app-root/logs/haproxy.log <==
[WARNING] 009/181452 (443835) : Server express/local-gear is UP (leaving maintenance).
[WARNING] 009/181453 (443835) : Server express/local-gear is DOWN, reason: Layer7 wrong status, code: 404, info: "Not Found", check duration: 36ms. 0 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
[ALERT] 009/181453 (443835) : proxy 'express' has no server available!
==> app-root/logs/nodejs.log <==
Error: ENOENT, stat '/var/lib/openshift/539976e05004467473000668/app-root/runtime/repo/app/index.html'
I'm reading around the hapoxy stuff though I'm not too clued into it?
Haproxy needs your app to serve something with http 200 OK response code, from root path (http://domain.name). Otherwise it will report your gear is DOWN. You may try checking the app with curl from the app's own gear, see the deployment log for IP and port.
To serve the static files from a selected folder (here "/app") without worrying about type recognition, you can use:
app.use(express.static(__dirname + '/app'));
If the native mime types are not enough, you can extend them:
express.mime.type['ogv'] = 'video/ogg';
Otherwise, see Basic static file server in NodeJS for a 'manual' implementation of static file server.
see: http://expressjs.com/api.html

How to redirect multiple subdomains to the same running express app

I'm building a SaaS app in NodeJS and using the Express framework. The individual members of the website has a url with a custom subdomain to login.
For example, a company called ABC Corp may login at abc.example.com and another company called Sony may login at sony.example.com
Any idea how I can redirect/route multiple subdomains to the same app instance?
You can use the express-subdomain package. Assuming you have a routes folder, containing abc.js and sony.js files that respectively export login routes for the abc and sony subdomains, you could have the following in index.js or whatever file from which your express server is listening.
const subdomain = require('express-subdomain');
const express = require('express');
const app = express();
const abcRoutes = require('./routes/abc');
const sonyRoutes = require('./routes/sony');
const port = process.env.PORT || 3000;
// use the subdomain middleware
app.use(subdomain('abc', abcRoutes));
app.use(subdomain('sony', sonyRoutes));
// a simple get route on the top-level domain
app.get('/', (req, res) => {
res.send('Welcome to the Home Page!');
});
// add any other needed routes
module.exports = app.listen(port, () => {
console.log('Server listening on port ' + port);
});
Your server will then be live and working as expected
http://example.com/ --> Welcome to the Home Page!
http://abc.example.com/login --> (Your login page for abc)
http://sony.example.com/login --> (Your login page for sony)
To tests subdomains locally you need to add them to your /etc/hosts file. (it requires sudo permissions)
127.0.0.1 localhost
127.0.0.1 example.com
127.0.0.1 abc.example.com
127.0.0.1 sony.example.com
The equivalent for /etc/hosts file on windows is at %systemroot%\system32\drivers\etc
For better details on setting up localhost domains locally check here
You can do more with the subdomain package. It accepts wildcards and you can use it to check API keys if you need such a feature.
Checkout the documentation for the express-subdomain package at https://npmjs.com/package/express-subdomain
You can actually handle that particular route or a wide range then go for Reg Exp (which allows you to do this app.get(new RegExp('(your|string)\/here'), function…) which you want to redirect and then follow the redirecting action something like below code is doing:
response.writeHead(302, {
'Location': 'yourpath/page.html'
//add other headers here...
});
response.end();
Update 1 : [as per the comments and other updates]
Then you try to handle all requests with the following app:
express()
.use(express.vhost('abc.example.com', require('/path/to/loginApp').app))
.use(express.vhost('sony.example.com', require('/path/to/loginApp').app))
.listen(80)
where /path/to/loginApp can be absolute paths or relative paths.
I hope this solves your problem.
Update 2:
Actually when a request comes in the request event is raised on a HTTP Server. So basically it is handled by express, express.vhost is a middle-ware function which raises the request event on another instance of a HTTP Server, that is how it works.
Below is the code:
function vhost(req, res, next){
if (!req.headers.host) return next();
var host = req.headers.host.split(':')[0];
if (req.subdomains = regexp.exec(host)) {
req.subdomains = req.subdomains[0].split('.').slice(0, -1);
server.emit('request', req, res);
} else {
next();
}
};

Resources