【问题标题】:Single port route to different services到不同服务的单端口路由
【发布时间】:2020-09-08 17:09:13
【问题描述】:

我的问题是:http-proxyreverse-proxy.js 或任何其他库(除了像 nginx 这样的网络服务器)是否能够根据 url 将来自端口 80 的所有请求路由到另一个服务?

如果一个请求来自端口 80,该 URL 为 localhost:80/route1,我想将其重定向到 localhost:3001 的服务

如果一个请求来自 80 端口,带有该 URL localhost:80/another-route,我想将它重定向到 localhost:3002 的服务。等等……

总结一下:我想暴露 1 个端口(80),然后根据请求中的 URL 模式将请求路由到其他服务。 到目前为止,我使用reverse-proxy.js 在下面尝试了这种方法,但它仅在端口更改时才有效

{
  "port": 80,
  "routes": {
    "localhost/test": "localhost:3001",
    "localhost/another-route": "localhost:3002",
    "localhost/another-route-same-service": "localhost:3002",
    "*": 80
  }
}

【问题讨论】:

    标签: javascript node.js reverse-proxy http-proxy node-http-proxy


    【解决方案1】:

    是的,当然可以。这是一个非常普遍的要求。在 Node 中,您可以使用流在本地完成它。这是一个仅使用标准 Node http 库的完整工作示例。

    const http = require('http');
    const server = http.createServer();
    
    let routes = {
        '/test': {
            hostname: 'portquiz.net',
            port: 80
        }
    }
    
    function proxy(req, res){
        if (!routes[req.url]){
            res.statusCode = 404;
            res.end();
            return;
        }
    
        let options = {
            ...routes[req.url],
            path: '', // if you want to maintain the path use req.url
            method: req.method,
            headers: req.headers
        }
    
        let proxy = http.request(options, function(r){
            res.writeHead(r.statusCode, r.headers);
            r.pipe(res, { end: true });
        })
    
        req.pipe(proxy, { end: true }).on('error', err => console.log(err))
    }
    
    server.on('request', proxy);
    server.listen(8080);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多