node--http-proxy

代理转发

访问3000端口,会被转发到5000端口,页面显示port 5000

服务a

//a.js
const app = require('http')
const httpProxy = require('http-proxy')
const proxy=httpProxy.createProxyServer()
app.createServer((req, res) => {
    proxy.web(req,res,{
        target:'http://localhost:5000'
    })
}).listen(3000, () => {
    console.log('run server 3000 ')
})

服务b

//b.js
const app = require('http')
app.createServer((req, res) => {
    res.end('port 5000')
}).listen(5000, () => {
    console.log('run server')
})

模拟nginx反向代理

监听同一个端口,根据上下文,分发到不同的服务上。代理机和两台服务分别跑在8080,3000,3001端口。

  • 访问:http://localhost:8080/server/1 页面显示==>server1
  • 访问:http://localhost:8080/server/2 页面显示==>server2

代理机proxy

const app = require('http')
const httpProxy = require('http-proxy')
const url = require('url')
const proxy = httpProxy.createProxyServer()
//代理路径映射 相当于nginx的 proxy_pass
const map = {
    '/server/1': 'http://localhost:3000',
    '/server/2': 'http://localhost:3001',
}
app.createServer((req, res) => {
    const {pathname} =url.parse(req.url)
    if (pathname === '/favicon.ico') return res.end()
    proxy.web(req, res, {
        target: map[pathname]
    })
}).listen(8080, () => {
    console.log('run server 8080 ')
})

服务机1

const app = require('http')
app.createServer((req, res) => {
    res.end('server1')
}).listen(3000)

服务机2


const app = require('http')
app.createServer((req, res) => {
    res.end('server2')
}).listen(3001)

再会


情如风雪无常,

却是一动既殇。

感谢你这么好看还来阅读我的文章,

我是冷月心,下期再见。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值