Reputation: 478
Hi I am trying to build a really simple "API-gateway" to demonstrate a small scale microservice project. I am using Nodejs and Express and I wanted to write a really simple public facing api-gateway server to route requests to my different microservices. For example lets say I have microservice A B and C. I wanted requests to localhost:3000/api/A to go to microservice A and return the result and then all other requests to localhost:3000/api/B go to microservice B and return the result ect. I wanted to write this instead of using NGINX, could someone help me understand how I can achieve this? (Most of my other "microservices" are also nodejs/express apis)
Could I get a quick simple example in code? I would love to see a GET request to google and then the client be able to get the GET request. (use of other libraries or modules would be cool too! :D)
Upvotes: 1
Views: 1612
Reputation: 673
You can run B on port 3001, C on 3002.
Then dispach all request by A on port 3000.
You can use Http client like axios in A to request B or C.
A.js
const express = require('express')
const axios = require('axios')
const app = express()
app.get('/api/B', (req, res) => {
axios.get('http://localhost:3001/dosomething', {
params: {...req.query, name: 'Device A'}, //Fetch datas from params
}).then(result => {
res.send(result)
})
})
app.get('/api/C', (_, res) => {
axios.get('http://localhost:3002/dosomething').then(result => {
res.send(result)
})
})
app.listen(3000, () => console.log('On 3000'))
B.js
const express = require('express')
const app = express()
app.get('/dosomething', (req, res) => {
const data = req.query
//Do something with data fetched here you know...
res.send('No worry, I will do something for ' + data.name)
})
app.listen(3001, () => console.log('On 3001'))
Upvotes: 2
Reputation: 96
If all micro-services are deployed on the same machine(different machines just need a bit more syncing to know ports/ips but that should not be an issue), you just use a common file to store ops/ports and then just redirect calls from route ip:3000/api/A to ipA:portA
Upvotes: 0