如何将NodeJS请求路由到另一个NodeJS应用? [英] How to route nodejs requests to another nodejs application?

查看:33
本文介绍了如何将NodeJS请求路由到另一个NodeJS应用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试构建一个非常简单的"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中使用http客户端(如axios)来请求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'))

这篇关于如何将NodeJS请求路由到另一个NodeJS应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆