Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Reverse Proxy using Express Server
I often run multiple apps on my server and often I am serving back end and front end from same Domain Name. So let’s deep dive into how can we serve back end and front end app, basically two different apps listing on the different port through one domain.
Made with https://www.draw.io/
As you can see in the above image backend is running on 3000 port and frontend is running on 5000 port. If client sends a request on the app running on port 4000 ( reverse proxy server) it will look for a target if the URL ends with /api/*. It will forward that request to the backend(3000) and if URL ends with /client/*. It will forward it to frontend(5000).
We are going to use the Express server to built our proxy server. In order to run the express server, you will the latest version of node installed in your machine. Download it from here and install it. Now go to your project directory where you want to create this reverse proxy server and run following commands.
npm initnpm install expressnpm install express-http-proxynpm install request
You will see package.json is created in your project directory. Now create the server.js file and paste below code inside it.
const proxy = require('express-http-proxy');
const app = require('express')();
const express = require('express')
const request = require('request');
app.use('/api', proxy('http://localhost:3000')); // this will proxy all incoming requests to /api route to back end
app.use('/client', proxy('http://localhost:5000')); // this will proxy all incoming requests to /client route to front end
app.listen(4000, () => {
request('http://localhost:5000', function (err, res, body) {
if(err === null){
console.log('backend is reachable from proxy server')
} else{
console.log('backend is not reachable from proxy server')
}
});
request('http://localhost:3000', function (err, res, body) {
if(err === null){
console.log('frontend is reachable from proxy server')
} else{
console.log('frontend is not reachable from proxy server')
}
});
});
Now is the easiest part, just run below command to run proxy server and make sure your backend and frontend are live at that time.
node server.js // you can user forever or pm2 to run it in infinite loop
There you go if you are now serving two different apps from one port.
As always here is some programming humor for you
Stop it Patrick, you’re scaring him 😄
Reverse proxy using express server was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.