繁体   English   中英

节点 http-proxy 和 express

[英]Node http-proxy and express

我正在尝试做这样的事情:

// Setup prox to handle blog requests
httpProxy.createServer({
    hostnameOnly: true,
    router: {
        'http://localhost': '8080',
        'http://localhost/blog': '2368' 
    }
}).listen(8000);

以前我是用这个:

http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});

基本上,我仍然想使用 express ...但是,当人们访问http://localhost/blog会被带到博客但仍然通过port 8080 (最终将是端口 80)提供服务

所以我把它换成了这个,效果更好。 问题是快递接管了路由(据我所知)

var options = {
    // pathnameOnly: true,
    router: {
        'localhost': 'localhost:8080',
        'localhost/blog': 'localhost:2368'
    }
}

// Setup prox to handle blog requests
var proxyServer = httpProxy.createServer(options);
proxyServer.listen(9000);

require('./app/server/router')(app);

http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});

将 http-proxy 1.0 与 express 一起使用:

var httpProxy = require('http-proxy');

var apiProxy = httpProxy.createProxyServer();

app.get("/api/*", function(req, res){ 
  apiProxy.web(req, res, { target: 'http://google.com:80' });
});

一个非常简单的解决方案,使用express-http-proxy无缝工作,并使用 cookie/身份验证:

var proxy = require('express-http-proxy');

var blogProxy = proxy('localhost/blog:2368', {
    forwardPath: function (req, res) {
        return require('url').parse(req.url).path;
    }
});

然后简单地:

app.use("/blog/*", blogProxy);

我知道我加入这个聚会迟到了,但我希望这对某人有所帮助。

我得到了这个工作。

  • 安装 Ghost并确保它的工作属性(默认端口为 2368)
  • 使用 express(侦听端口 80)创建您的节点 Web 应用程序 - 这里没什么特别的
  • 在您的 Web 应用程序中安装node-http-proxy npm install http-proxy
  • 为代理对 Ghost 服务的请求的 /blog* 创建通配符路由

    var httpProxy = require('http-proxy'); var proxy = new httpProxy.RoutingProxy(); app.get('/blog*', function (req, res, next) { proxy.proxyRequest(req, res ,{ host: 'moserlap.splitvr.com', port: 2368 }); });
  • 更新 Ghost 配置以使用子目录(仅在 0.4.0+ 中支持)

     config = { // ### Development **(default)** development: { // The url to use when providing links to the site, Eg in RSS and email. url: 'http://127.0.0.1/blog', ...
  • 您现在应该可以访问http://yoursite.com/blog并且所有路由都可以正常工作。

我使用了简单的解决方案来代理我的 GET/POST 请求。

var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();

app.post("/api/*", function(req, res) {
  apiProxy.web(req, res, { target: 'http://localhost:5000'})
});
app.get("/api/*", function(req, res) {
  apiProxy.web(req, res, { target: 'http://localhost:5000'})
});

处理所有类型请求的另一种更简单的方法是:

app.all("/api/*", function(req, res) {
  apiProxy.web(req, res, { target: 'http://localhost:5000'})
});

注意:以上函数必须在bodyparser之前。

暂无
暂无

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

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