http-party / node-http-proxy

A full-featured http proxy for node.js
https://github.com/http-party/node-http-proxy
Other
13.88k stars 1.97k forks source link

how to build reverse proxy middleware for express #808

Open pwasem opened 9 years ago

pwasem commented 9 years ago

Hi,

I' am trying to build a reverse proxy with expressjs and node-http-proxy. UI and API Services should be dynamically mounted with expressjs and requests should be forwarded via node-http-proxy.

e.g. UI: source.com/service/ui ---> sometarget.com/some/path/ui API: source.com/service/api ---> othertarget.com/some/other/path/to/api

forward.js (middleware using node-http-proxy)


var forward = function(target) {

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

    var proxy = httpProxy.createProxyServer();

    proxy.on('proxyReq', function (proxyRequest, request, response, options) {

        console.log('how to manipulate proxy request here?');

    });

    proxy.on('proxyRes', function (proxyResponse, request, response) {

        console.log('how to manipulate proxy response here?');

    });

    var middleware = function(request, response, next) {

            proxy.web(request, response,{

            'target': target
            // TODO what options are needed here?
        });
    };

    return middleware;
};

module.exports = forward;

app.js (using expressjs)


    var express = require('express');
    var forward = require('./lib/forward.js');

    var app = express();

    // some token based authentication middleware
    app.use(authenticate());

    // services will be added dynamically here, request only get here on a successful authenticate()
    app.use('/service/ui/*', forward('sometarget.com/some/path/ui'));
    app.use('/service/ui/*', forward('othertarget.com/some/other/path/to/api'));

    app.listen(80);

My problem One time api and ui request are forward correctly, but if I have an ui that has some link (a href='/internal/link/of/that/ui') following that link results in a Cannot GET '/internal/link/of/that/ui' because the '/service/ui/' is not prepended.

How can this be fixed? Do I need to "regexp the response.body" myself? if yes, how to do this? or is there some option I can provide to proxy.web()?

Thank you very much in advance!

tanaydin commented 9 years ago

Hi there,

I workaround this problem with playing with proxyRequest.path value like so

proxy.on('proxyReq', function (proxyRequest, request, response, options) {
    if (proxyRequest.path == '/service/api') {
        proxyRequest.path = '/some/other/path/to/api';
    }
});
h2non commented 9 years ago

I've a similar scenario that you and I've just made this package to deal with that kind of requirements.

Hope it could be useful in some or other way: https://github.com/h2non/rocky