Proxy with express.js


To avoid same-domain AJAX issues, I want my node.js web server to forward all requests from URL /api/BLABLA to another server, for example, and return to user the same thing that this remote server returned, transparently.

All other URLs (beside /api/*) are to be served directly, no proxying.

How do I achieve this with node.js + express.js? Can you give a simple code example?

(both the web server and the remote 3000 server are under my control, both running node.js with express.js)

So far I found this , but reading the documentation there didn't make me any wiser. I ended up with

var proxy = new httpProxy.RoutingProxy();
app.all("/api/*", function(req, res) {
    console.log("old request url " + req.url)
    req.url = '/' + req.url.split('/').slice(2).join('/'); // remove the '/api' part
    console.log("new request url " + req.url)
    proxy.proxyRequest(req, res, {
        host: "",
        port: 3000

but nothing is returned to the original web server (or to the end user), so no luck.

8/10/2013 2:54:20 PM

Accepted Answer

You want to use http.request to create a similar request to the remote API and return its response.

Something like this:

var http = require('http');

/* your app config here */'/api/BLABLA', function(req, res) {

  var options = {
    // host to forward to
    host:   '',
    // port to forward to
    port:   80,
    // path to forward to
    path:   '/api/BLABLA',
    // request method
    method: 'POST',
    // headers to send
    headers: req.headers

  var creq = http.request(options, function(cres) {

    // set encoding

    // wait for data
    cres.on('data', function(chunk){

    cres.on('close', function(){
      // closed, let's end client request as well 

    cres.on('end', function(){
      // finished, let's finish client request as well 

  }).on('error', function(e) {
    // we got an error, return 500 error to client and log error



Notice: I haven't really tried the above, so it might contain parse errors hopefully this will give you a hint as to how to get it to work.

5/1/2014 4:44:24 PM

I did something similar but I used request instead:

var request = require('request');
app.get('/', function(req,res) {
  //modify the url in any way you want
  var newurl = '';

I hope this helps, took me a while to realize that I could do this :)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow