20

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

// 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'));
});
4

4 回答 4

44

将 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' });
});
于 2014-03-07T07:30:37.873 回答
9

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

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);

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

于 2015-09-24T12:16:51.070 回答
4

我得到了这个工作。

  • 安装 Ghost并确保其正常工作(默认端口为 2368)
  • 使用 express 创建你的 node web 应用程序(监听端口 80)——这里没什么特别的
  • 在您的网络应用程序中安装node-http-proxy npm install http-proxy
  • 为 /blog* 创建通配符路由,将请求代理到 Ghost 服务

    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, E.g. in RSS and email.
      url: 'http://127.0.0.1/blog',
    ...
    
  • 您现在应该可以访问http://yoursite.com/blog并且所有路由都可以正常工作。

于 2014-01-15T23:32:24.073 回答
2

我使用简单的解决方案来代理我的 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之前。

于 2020-04-16T17:14:36.800 回答