Open In App

How to set Multiple Web Apps with Different Base Directories on the Same Express Server ?

Node.js supports server side functionality using Express. It allows us to add new features and organize the functionalities. While working with Express, we can set up our own local server for a given base directory. The following approach covers how to serve multiple web apps with different base directories on the same express server.

Setting up environment and Execution:



Step 1: Initialize node.js project with the following command.

npm init

Step 2: Install the required module using the following command.



npm install express

Step 3: After installing express, we can require the module using the following code.

const express = require('express');
const app = express();

The app.listen() helps to bind the application with a specified host and port. Thus, we can set up multiple applications on different ports while working with the same express server. 

Step 4: Create an index1.js file with the following code. We are using port 3000. We are currently sending a simple message that represents the first application.

index1.js




// Requiring express
const express= require('express');
const app = express();
  
// Sending message for first application
app.get("/",function(req,res){
  res.send('<p>This is GFG application 1</p>')
});
  
// Listening on port 3000
app.listen(3000,function(){
  console.log("Server is running on port 3000");
});

Step 5: Run index1.js file using the following command.

node index1.js

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Step 6: Create an index2.js file with the following code. We are using port 4000. We are currently sending a simple message that represents the second application.

index2.js




// Requiring express
const express= require('express');
const app = express();
  
// Sending message for second application
app.get("/",function(req,res){
  res.send('<p>This is GFG application 2</p>')
});
  
// Listening on port 4000
app.listen(4000,function(){
  console.log("Server is running on port 4000");
});

Step 7: Run index2.js file using the following command.

node index2.js

Output: Now open your browser and go to http://localhost:4000/, you will see the following output:


Article Tags :