lonelymo
lonelymo

Reputation: 4182

Express JS wild card route proxying

I am using express-http-proxy to proxy a backend server. I would like all requests to /proxy viz /proxy/apples/brand or /proxy/oranges/brand/nnnn etc to be proxied to the backend service.

So, I have a wild card proxy set up here.

    '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 + '.')
    });

I expect this https://localhost:3000/proxy/oranges/brand/nnnn to be proxied to https://backend-server.com/oranges/brand/nnnn

But I just get

Cannot GET /proxy/aa

.I am not sure what's wrong here. The wild card routing looks pretty ok. Any thoughts here?

Upvotes: 1

Views: 995

Answers (1)

ioncreature
ioncreature

Reputation: 521

You could try request module. This solution perfectly works for me

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

Or if you still want to use express-http-proxy you need to write

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

Upvotes: 2

Related Questions