[英]How to route nodejs requests to another nodejs application?
嗨,我正在嘗試構建一個非常簡單的“API 網關”來演示一個小型微服務項目。 我正在使用 Nodejs 和 Express,我想編寫一個非常簡單的面向公眾的 api 網關服務器來將請求路由到我的不同微服務。 例如,假設我有微服務 AB 和 C。我希望對 localhost:3000/api/A 的請求轉到微服務 A 並返回結果,然后對 localhost:3000/api/B 的所有其他請求轉到微服務 B 並返回結果等。 我想寫這個而不是使用 NGINX,有人可以幫助我了解如何實現這一目標嗎? (我的大多數其他“微服務”也是 nodejs/express apis)
我能在代碼中得到一個簡單的例子嗎? 我很想看到向 google 發出 GET 請求,然后客戶端能夠獲得 GET 請求。 (使用其他庫或模塊也很酷!:D)
您可以在端口 3001 上運行 B,在 3002 上運行 C。
然后在端口 3000 上發送 A 的所有請求。
您可以在 A 中使用像 axios 這樣的 Http 客戶端來請求 B 或 C。
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'))
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'))
如果所有微服務都部署在同一台機器上(不同的機器只需要更多的同步來了解端口/ip,但這應該不是問題),您只需使用一個公共文件來存儲操作/端口,然后只需重定向調用從路由 ip:3000/api/A 到 ipA:portA
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.