简体   繁体   English

node.js http代理重定向

[英]node.js http-proxy redirect

How can I follow redirects using http-proxy module in node.js, so I can keep the same url in the browser? 如何在node.js中使用http-proxy模块跟踪重定向,以便在浏览器中保留相同的url?

I've a two web sites (A and B) behind the reverse proxy, the user access site A thru the revere proxy perfectly , but there is a in site A to site B that makes url in the browser change to site B, it should still display the reverse proxy url in the browser 我在反向代理后面有两个网站(A和B),用户访问站点A到revre代理完美无缺,但是站点A到站点B的内部站点使浏览器中的url更改为站点B,它仍应在浏览器中显示反向代理URL

This is my current code 这是我当前的代码

var port = process.env.PORT;

var http = require('follow-redirects').http,
    httpProxy = require('http-proxy'),
    url = require('url');

// http Server 
var proxy = new httpProxy.createServer({});

var httpServer = http.createServer(function (req, res) {

    console.log('request received: ' + req.path);    

    var target = 'http://siteA/';

    if (!req.url.toString().endsWith('/')) {
        target = target + '/';
    }
    if (req.url.toString() != '/') {
        target = target + req.url;
    }

    console.log('routing request to ' + target);

    var urlObj = url.parse(req.url);

    req.headers['host'] = urlObj.host;
    req.headers['url'] = urlObj.href;

    proxy.proxyRequest(req, res, {
        host: urlObj.host,
        target: target,
        enable: { xforward: true }
    }); 
});

httpServer.listen(port);

console.log("server listening at port: " + port);

String.prototype.endsWith = function (s) {
    return this.length >= s.length && this.substr(this.length - s.length) == s;
}

String.prototype.startsWith = function (str) {
    return this.indexOf(str) == 0;
};

I'm going to post this answer even though I suspect you won't believe it, but what you are hoping to do is not feasible using your approach. 即使我怀疑您不会相信,我也将发布此答案,但是您希望使用此方法不可行。 The web just doesn't work like that. 网路无法正常运作。 I elaborate why this is true in this answer . 我将详细解释为什么这个答案是正确的。 What DOES work like this is having your users configure your node proxy as a proxy server in their browser settings and then putting their destination URLs in the browser address bar as they normally would. 这样做的作用是让用户在其浏览器设置中将您的节点代理配置为代理服务器,然后像往常一样将其目标URL放在浏览器地址栏中。 That's how the web supports transparent proxies. 这就是网络支持透明代理的方式。 Trying to do it by having users put your proxy address in their address bar is not feasible as a general-purpose approach because the web is not composed exclusively of relative links in static HTML pages. 尝试通过让用户将您的代理地址放在其地址栏中来进行此操作作为通用方法是不可行的,因为Web并非仅由静态HTML页面中的相对链接组成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM