首页 > 解决方案 > 到不同服务的单端口路由

问题描述

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

如果带有该 url 的请求来自端口 80,localhost:80/route1我想将其重定向到服务localhost:3001

如果带有该 url 的请求来自端口 80,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
  }
}

标签: javascriptnode.jsreverse-proxyhttp-proxynode-http-proxy

解决方案


是的,当然可以。这是一个非常普遍的要求。在 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);

推荐阅读