简体   繁体   中英

Run a custom function when using the routing table on a reverse proxy with node-http-proxy

I have found it's easy to use node-http-proxy to route a sub-directory to different ports on a local server. However, I haven't found if there's a way to run a custom function when doing the routing. What I want to do is:

  1. If the service on the target port is not running, start it up, then finish the route
  2. If the service is already running on the target port, just do the route

I'm not asking about how to check for the service and start it, just how to have a function called each time a re-route is going to take place.

Can I do something like this?

var options = {
    route: {
        '/task1' : customFunc('3000'),
        '/task2' : customFunc('3001'),
    }
}

httpProxy.createServer(options).listen(80);

You cannot assign a function as the path value, as that value is parsed as a URL. See here .

Instead, what you can do is intercept the requests before it hits the router, start your services as needed, and then forward the request back to the router:

var init = function(req, res, next){
    if(req.url.indexOf('task1') > -1 && !serviceIsRunning()){
        startService();
        next(); // forward req back to router
    } else {
        // no need to do anything, move request along
        next();
    }    
}

httpProxy.createServer('localhost', options, init).listen(80);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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