Here's a basic example using Node.js and Express:
Step 1: Install dependencies
npm install express http-proxy-middleware
Step 2: Create gateway.js
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
// Service Proxies
app.use('/service1', createProxyMiddleware({ target: 'http://localhost:3001', changeOrigin: true }));
app.use('/service2', createProxyMiddleware({ target: 'http://localhost:3002', changeOrigin: true }));
// Start the Gateway
app.listen(3000, () => {
console.log('API Gateway running on http://localhost:3000');
});
Step 3: Create services
Create service1.js and service2.js to represent two different backend services.
service1.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Response from Service 1');
});
app.listen(3001, () => {
console.log('Service 1 running on http://localhost:3001');
});
service2.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Response from Service 2');
});
app.listen(3002, () => {
console.log('Service 2 running on http://localhost:3002');
});
Step 4: Run the services and the gateway
Open three terminal windows and run the following commands:
Terminal 1:
node service1.js
Terminal 2:
node service2.js
Terminal 3:
node gateway.js
Now, you can access the services via the API Gateway:
- http://localhost:3000/service1
- http://localhost:3000/service2