【问题标题】:Get server URL from Express when using it as a proxy使用 Express 作为代理时从 Express 获取服务器 URL
【发布时间】:2021-11-11 00:21:11
【问题描述】:

我使用expressexpress-http-proxy 作为我的一些应用程序的代理。我有特定的子域作为我的应用程序的一部分,我想获得它的价值。

例如,我通过 curl 向我的代理发出请求

curl google.com --proxy https://subdomainX.localhost:8000

我想读取subdomainX 的值。但是,Express 请求仅包含我要代理到的域(在本例中为 google.com)的 url 和主机值。

如果可能的话,我想读取我自己服务器的请求。

这是以下示例服务器代码:

import express from "express";
import proxy from "express-http-proxy";

const proxyApp = express();

proxyApp.use((req, res, next) => {
// I'd like to get the subdomain subdomainX here
// so I can perform logic with it
const subdomain = req.headers.host // this is google.com
if (subdomain === "subdomainX") {
    next();
    return;
}

    res.send("Not authorized");
});

proxyApp.use(
    proxy(
        (req) => {
            return req.protocol + "://" + req.get("host");
        },
        {
            https: true,
        }
    )
);

【问题讨论】:

    标签: javascript node.js express proxy


    【解决方案1】:

    客户端通过域名服务器将代理的主机名解析为 IP 地址,然后连接到该 IP 地址。然后它使用这个连接发送一个 HTTP 请求,看起来像

    GET http://google.com HTTP/1.1
    Host: google.com
    

    并且不包含代理主机名的任何痕迹。

    只有域名服务器知道代理的主机名,而不是代理服务器本身。

    但是,如果您的应用程序能够为不同的请求指定不同的代理主机名,它同样可以在请求中指定一个额外的标头,并且您“可以使用该标头执行逻辑”。然后客户会

    curl google.com -H "X-Proxy-Subdomain:subdomainX" --proxy https://localhost:8000
    

    并且您的代理会在将请求转发到 google.com 之前删除该标头。

    附加说明:您上面提供的代码仅在客户端发出 HTTP 请求时才有效。如果客户端发出 HTTPS 请求,代理将只能在 connect 事件中看到它,而不是在中间件函数中看到。

    【讨论】:

    • 感谢您的回答,这为为什么这不起作用提供了一些有价值的见解。
    猜你喜欢
    • 1970-01-01
    • 2016-11-11
    • 2016-05-04
    • 2022-11-15
    • 2015-02-12
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多