How to add proxy to Node / Express site? How to add proxy to Node / Express site? json json

How to add proxy to Node / Express site?


  1. See node-http-proxy. It should be better than implementing your own proxy.

  2. Express lets you add middlewares as arguments when you do express.createServer(). Or, you can add them afterwards by using .use(proxy).

  3. I don't think so.

To give an example (untested code):

var httpProxy = require('http-proxy'), express = require('express');var yahooProxy = httpProxy.createServer(80, 'yahoo.com');var app = express.createServer();app.configure(function () {    app.use('/yahoo', yahooProxy);});...


Here's another example with 1.0.X that demonstrates header injection.

var express = require( 'express' );var proxy   = require( 'http-proxy' ).createProxyServer;var app     = express();app.configure(function() {  // Inject some request headers here before we proxy...  app.use( function( req, res, next ) {    req.headers[ 'x-my-header' ] = 'blah blah';    next();  });  // Proxy based on path...  app.use( '/stack', proxy({ target: 'http://stackoverflow.com'} ).web );  app.use( '/yahoo', proxy({ target: 'http://yahoo.com'} ).web );  app.use( function( req, res ) {    res.send({ ok: false, message: 'Not much here.' })  });}).listen( 3000 );


You can just add another route to your express app, perhaps at /api/yahoo/....

This view function will then make a call to the Yahoo API, probably using: http://nodejs.org/docs/v0.4.9/api/http.html#http.request, and then when that request finishes you simple return the result as JSON.

However, keep in mind that your proxy is public and that anyone can make requests through it. I would suggest some basic authorization. A generated value which you provide to the page making the request should work.