How can I have multiple node applications on nodejs server? - node.js

I am trying to merge two (or more) nodejs apps. 1st is login application that takes you to your dashboard. When you are there you should see another app that is dedicated to you, that runs on different local IP and port.
So for login I am using Okta express login portal that grabs user data from Okta servers. Now this is dashboard in pug
block content
h2.text-center Dashboard
h2.user.profile.profileUrl
.row
.offset-sm-2.col-sm-8
.jumbotron.text-center.
Welcome to your dashboard page, #{user.profile.firstName}.
#{user.profile.profileUrl}.
and looks like this
dashboard
now I want that user.profle.profileURL actually opens when clicked on control panel but address not to be visible in browser so address would be same xydomain/dashboard
is it that possible?

Yes its possible.
The technology you want is node js reverse proxy. You want to create multiple server on same machine or different machine, but with same domain, but after the domain extension, the different url points to different server.
If multiple server on same local machine, use different port numbers! If different machines, use the ip number of the machine and its port number. Make sure firewalls are open for the ports!
Here's a reference for you to get you started: https://codeforgeek.com/reverse-proxy-using-expressjs/
Basic understanding is create the 3 different servers. For same machine, use different port numbers.
Then create a server and get that pointing to the different servers when the url is hit.
On all servers, run this command to setup node:
npm init -y
npm i -S express http-proxy
These are the codes for all 4 servers.
eg server1:
var express = require("express");
var app = express();
app.get('/app1',function(req,res) {
res.send("Hello world From Server 1");
});
app.listen(3001);
server2:
var express = require("express");
var app = express();
app.get('/app2',function(req,res) {
res.send("Hello world From Server 1");
});
app.listen(3002);
Server3:
var express = require("express");
var app = express();
app.get('/app3',function(req,res) {
res.send("Hello world From Server 1");
});
app.listen(3003);
Reverse Proxy Server:
var express = require('express');
var app = express();
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var serverOne = 'http://localhost:3001',
ServerTwo = 'http://localhost:3002',
ServerThree = 'http://localhost:3003';
app.all("/app1/*", function(req, res) {
console.log('redirecting to Server1');
apiProxy.web(req, res, {target: serverOne});
});
app.all("/app2/*", function(req, res) {
console.log('redirecting to Server2');
apiProxy.web(req, res, {target: ServerTwo});
});
app.all("/app3/*", function(req, res) {
console.log('redirecting to Server3');
apiProxy.web(req, res, {target: ServerThree});
});
app.listen(3000);
Now run ALL 4 servers.
Now go to url, type in:
localhost:3000/app1/ and it goes to your server 1
localhost:3000/app2/ and it goes to your server 2
localhost:3000/app3/ and it goes to your server 3
If you're on different local machine, change localhost to the ip numbers.
If you don't like using the / after app1, then you need to configure it. This is outside the scope of this question.
Good luck to you.
Edit: I forgot to mention, your original pug file you put into your reverse proxy server. It's homepage, you render your dashboard page in your proxy server.

Related

React app (via create-react-app) with Express backend in single Azure app?

I have a React front-end app with an express backend that's working locally as a proxy API server.
In my local dev environment, the React fonr-end is running on port 3001, with the Express server running on port 3000.
In my package.json, I have the proxy set up:
"proxy": "http://localhost:3000",...
The app is deployed via an Azure pipeline, which builds the app and the server, zips them up, and copies the artefacts to an Azure domain.
In the Azure app's Configuration, I have the following Startup Command:
node server & npx serve -s
This should (in theory) start the Express server (which is set to listen on port 3000) and server the front-end. The front-end is indeed accessible, but when it tries to make a call to the api via a simple fetch request, it's returning the HTML of the React app instead of a JSON response. This indicates to me that it's not actually exposing the Express port to the front end.
Is it actually possible to server the Express server and the frontend as part of the same container?
It turns out that this approach - while it was the wrong one - was in fact working, but Azure App Services will only expose a single port. In this case, we could either expose the React front end via npx serve -s OR expose the api by setting the PORT variable to 3000. Both were running, but only one could be reachable.
The solution was to serve the React front-end via the Express server:
const path = require('path');
const { response } = require('express');
const express = require('express');
const request = require('request');
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, '../')));
app.use('/api', function (req, res, next) {
// API function calls here
...
});
app.get('*', function(req, res, next) {
res.sendFile(path.join(__dirname, '../index.html'));
});
app.set('port', 3000);
app.listen(app.get('port'), () => {
console.log('Proxy server listening on port ' + app.get('port'));
});
And set the PORT container variable to 3000.

Accessing Routes in Node inside in a Domain Name

I have a node app which is up on running on port 3000. i.e say 139.59.43.234:3000.
139.59.43.234 is my server ip.
Then I went to go daddy and assign a domain name say mydomain.nik.in which is pointing to 139.59.43.234:3000/SomeRoute.
If i then go to my browser and types mydomain.nik.in then it works properly. I can easily access my route.
This is my sample code.
var express = require('express');
var app = express();
app.get('/SomeRoute',(req,res) => { // Route 1
res.send('hello nikhil');
})
// here i have another route which i wants to access.
app.get('/SomeRoute/:id',(req,res) => { //Route 2
res.send('hello user');
})
app.listen(3000);
Now if I go to my browser and types "mydomain.nik.in/someId" then it redirects me to the SomeRoute method i.e on Route 1.
I don't know what I am doing wrong here.
I wants to access Route 2.
According to this, there should be a Wild Card Redirect option in GoDaddy settings. And it does exactly what you are asking for.

two node.js servers at one web address

I have two web application node.js servers and I need to have them under one web address.
It should work like this:
example.com/wa/* -> redirect to example.com:pppp
others example.com/* -> redirect to example.com:qqqq
I have experimented with http proxy module, but it doesn't work, maybe the problematic part is the fact, both servers are https not http.
Using Express you can do something like this
var express = require('express');
var http = require('http');
var app = express();
app.use('/wa/*', function(req, res){
req.redirect('example.com:pppp')
});
app.use('/*', function(req, res){
req.redirect('example.com:qqqq')
});
http.createServer(app);
Not tested, but it should work.
Note: The /wa/* route must come before the /* route. otherwise all requests will get redirected by the first middleware

Why combine http module with express module

Hello guys i'm new to node js and started researching and working on some tutorials. I just want a better understanding or clarification on a doubt i had. So i came across the in built module http. This helps in creating a a basic web server. Now express module is a web framework that is built on top the http module that makes it easy using a fully wedged web server without reinventing the wheel. Now I came across this code:
var express = require( 'express' )
, http = require("http")
http.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen(8080);
But in express one could simply just do this
var express = require('express');
var app = express();
app.listen(8080, function() {
console.log('Listening on ' + 8080);});
What's the difference between both? Don't they both accomplish the same thing. If not what's the difference and advantage of using the first approach. Should one adhere to the first approach as it's a good programming practice. That's my doubt as i just want a clear understanding if there's any difference.
Why combine http module with express module
There's really no reason to create your own http server using the http module. Express will just do that for you with app.listen() just fine and save you little bit of typing.
If you were creating an https server, then you would need to use the https module and pass security credentials to https.createServer(...) in order to create a properly configured server. Express does not have the ability to create a properly configured https server for you automatically.
If you look at the Express code in GitHub for app.listen(), it shows this:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, there's really no difference (other than a little less typing) when you use app.listen() or create your own http server and then use app as the listener to that server.
So, these two code snippets are identical in function:
var app = require('express')();
app.listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
The above code is functionally identical to:
var http = require('http');
var app = require('express')();
http.createServer(app).listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
Of course, if you're trying to set up https servers or add custom options to the .createServer() method, then you will set up your own server first and then pass app to it as the listener. app.listen(...) is just a shortcut when the default http.createServer() works fine.

Link one express js application to another

I have two Express JS application and I want to add a route for one inside the other so when this link is requested it goes to the sub-application. Is that possible??
Example:
The main application is accessed through the link www.linktoapp.com and it is written in Express js.
Now I have developed another Express js application and I want to access it through the link www.linktoapp.com/secondapp
My question is can I add this route (/sceondapp) in the main application so I can access it like I said?
Thanks.
You could always have two separate express processes running on 2 ports and then reverse proxy the requests.
https://github.com/nodejitsu/node-http-proxy
Your question is a bit confusing! What I understand from your question:
You have two expressjs application running. Two application can't run on same port. Two application can however run on two different ports. See example below.
var express = require("express");
var app1 = express(); //created the first app
var app2 = express(); //created the second app
app1.get("/",function(req,res){
res.send("<html><body><a href='/sec'>go second app</a></body></html>");
// created a link to app2
});
app1.get("/sec",function(req,res){ // redirection to second app
res.redirect("http://localhost:3001/");
})
app2.get("/",function(req,res){
res.send("welcome to second app");
});
app2.listen(3001,function(){ // app2 is listening on port 3001
console.log("app two is listening on 30001 ")
});
app1.listen(3000,function(){ // app2 is listening on 3000
console.log("app1 is listening on 3000");
});
What you want is to create an Express sub-app. Express sub-apps share routes, views, sessions, etc with the main app.
For example, let's say you want one node app, s_app.js, to be a sub-app of another, p_app.js.
s_app.js
var express = require('express');
var app = module.express = express();
// set routes for userjs
app.get('/path_1', function(req, res){
// display path_1
});
p_app.js
var express = require('express');
var app = express();
var s_app = require('s_app'); // mount s_app.js
app.use(s_app);
// now p_app and s_app share routes, views, sessions, etc
If you want more detail, take a look at a tutorial I wrote on how to build node.js sub-apps

Resources