gpt4 book ai didi

javascript - 如何将nodejs请求路由到另一个nodejs应用程序?

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:12 25 4
gpt4 key购买 nike

您好,我正在尝试构建一个非常简单的“API 网关”来演示小型微服务项目。我正在使用 Nodejs 和 Express,我想编写一个非常简单的面向公众的 api 网关服务器来将请求路由到我的不同微服务。例如,假设我有微服务 A B 和 C。我希望对 localhost:3000/api/A 的请求转到微服务 A 并返回结果,然后对 localhost:3000/api/B 的所有其他请求转到微服务 B 并返回结果等。我想写这个而不是使用 NGINX,有人可以帮助我理解如何实现这一点吗? (我的大多数其他“微服务”也是nodejs/express api)

我可以获得一个快速简单的代码示例吗?我希望看到向 google 发出 GET 请求,然后客户端能够获取 GET 请求。 (使用其他库或模块也很酷!:D)

最佳答案

您可以在端口 3001 上运行 B,在 3002 上运行 C。

然后在端口 3000 上调度 A 的所有请求。

可以在A中使用像axios这样的Http客户端来请求B或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'))

关于javascript - 如何将nodejs请求路由到另一个nodejs应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60260252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com