【问题标题】:Express JS wild card route proxyingExpress JS 通配符路由代理
【发布时间】:2015-10-02 10:46:13
【问题描述】:

我正在使用 express-http-proxy 代理后端服务器。 我希望 /proxy 即 /proxy/apples/brand 或 /proxy/oranges/brand/nnnn 等的所有请求都被代理到后端服务。

所以,我在这里设置了一个通配符代理。

    'use strict';

    var express = require('express');

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

    var app = express();

    // ""

    app.use('/proxy*', proxy('https://backend-server.com/' ,{
      forwardPath: function(req, res) {
        console.log(req.url)
        return require('url').parse(req.url).path;
      }
    }));



    var port = 3000;

    app.listen(port, function() {
        console.log('listening on port ' + port + '.')
    });

我期待这个 https://localhost:3000/proxy/oranges/brand/nnnn 被代理到 https://backend-server.com/oranges/brand/nnnn

但我只是明白了

无法获取 /proxy/aa

.我不确定这里出了什么问题。通配符路由看起来还不错。这里有什么想法吗?

【问题讨论】:

    标签: javascript node.js express proxy


    【解决方案1】:

    你可以试试request 模块。这个解决方案非常适合我

    var request = require( 'request' );
    app.all( '/proxy/*', function( req, res ){
        req.pipe( request({
            url: config.backendUrl + req.params[0],
            qs: req.query,
            method: req.method
        }, function( error, response, body ){
            if ( error )
                console.error( 'Wow, there is error!', error );
        })).pipe( res );
    });
    

    或者如果你还想使用express-http-proxy你需要写

    app.use( '/proxy/*', proxy('https://backend-server.com/', {
        forwardPath: function( req, res ){
            return req.params[0];
        }
    }));
    

    【讨论】:

    • 最终使用了请求。顺便说一句,后一个选项也不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多