13

I'm writing an express.js app and would like to serve certain routes from another server.

Express serves some routes starting with api.example.com/v1/*. I would like any paths starting with /ad/hoc/ to be forwarded to another server and the response served by Express, e.g. api.example.com/ad/hoc/endpoint.php would be piped to grampas-lamp-stack.example.com/ad/hoc/endpoint.php.

I can accomplish this with res.redirect but I'd like to stream the response through my Express app and avoid redirecting the browser to another IP address.

app.js

var express = require('express');
var app = express();

app.get('/v1/users/:id', UserCtrl.get);
app.get('/v1/users/search', UserCtrl.search);

app.get('/ad/hoc/*', function(req, res) {
  res.redirect('http://grampas-lamp-stack.example.com' + req.url);
}

I tried searching "proxy requests express" but I'm not sure if proxy is an accurate term for what I'm doing. If there's a better word for this topic or what I'm trying to accomplish, please let me know.

Eric
  • 1,511
  • 1
  • 15
  • 28
  • 1
    I think the right way to do it would be through NGINX or APACHE. Create a redirect rule. – andybeli Jun 23 '16 at 19:01
  • 1
    reverse proxy, i'd do it with nginx or apache before using express for this, though express can do it. – Kevin B Jun 23 '16 at 19:30
  • If anyone would care to explain the benefits of using Nginx or Apache for this, I'd love to see it posted as an answer. – Eric Jun 23 '16 at 21:21

1 Answers1

16

You can use express-http-proxy.

And yes, proxying is the accurate term for what you are looking for. It will underneath forward the request to another url, as the API will also imply.

Here's an example usage:

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

app.use('/route/you/want/proxied', proxy('proxyHostHere', {
    forwardPath: function (req, res) {
      return '/path/where/you/want/to/proxy/' + req.url
    }
}))
Eric
  • 1,511
  • 1
  • 15
  • 28
Elod Szopos
  • 3,475
  • 21
  • 32
  • What if I want to apply express-http-proxy middleware to just a single request like `app.get('/some/path', proxy(...))`? Is this doable? – Bruce Sun Jun 10 '20 at 11:20
  • There are changes in the mentioned module. Do not use the code mentioned here under assumption it will work out of the box. – Kumar Jul 16 '20 at 07:55