I have a ec2 Windows instance on AWS, which responds with a frontend on port 80. My backend is running on port 5000. Is there any way I can host both frontend and backend on same port without using any port on a client for the rest API?
Frontend:
www.example.com
Current Backend:
www.example.com:5000
What I'd like it to be:
www.example.com/backend/
How do I to write a single index.js or server.js file for both Backend and Frontend routes?
Service Endpoint
The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal Reference: Definition of service endpoint.
www
.example.comwww
api
.example.com (The most used)backend
.example.comYou can accomplish that using either a Reverse Proxy like Nginx or getting the Subdomain from the request object in NodeJs.
Nginx is a web server which can also be used as a reverse proxy, load balancer, and HTTP cache. The software was created by Igor Sysoev and first publicly released in 2004. A company of the same name was founded in 2011 to provide support.
Using Nginx as HTTP load balancer
You can configure Nginx to balance the requests to your server as follow:
http {
upstream backend {
server localhost:5000;
}
upstream frontend {
server localhost;
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://backend;
}
}
server {
listen 80;
server_name www.example.com example.com;
location / {
proxy_pass http://frontend;
}
}
}
Use expressjs to get the subdomain from request object.
An array of subdomains in the domain name of the request.
Documentation:
// Host: "tobi.ferrets.example.com"
req.subdomains
// => ["ferrets", "tobi"]
In your case your possible subdomains are: www
or api
// Host: "www.example.com"
req.subdomains
// => ["www"]
Or
// Host: "api.example.com"
req.subdomains
// => ["api"]
This is how you have to process the request within your server.js
var subDomain = req.subdomains[0];
if (subdomain === 'api') {
processBackendRequest();
} else {
processFrontendRequest();
}