6

I'm writing a node.js proxy server, serving requests to an API on different domain.

I'd like to use node-http-proxy and I have already found a way to modify response headers.

But is there a way to modify request data on condition (i.e. adding API key) and taking into account that there might be different methods request - GET, POST, UPDATE, DELETE?

Or maybe I'm messing up the purpose of node-http-proxy and there is something more suitable to my purpose?

Community
  • 1
  • 1
aliona
  • 447
  • 1
  • 6
  • 18

1 Answers1

3

One approach that makes it quite simple is to use middleware.

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

var apiKeyMiddleware = function (apiKey) {
  return function (request, response, next) {
    // Here you check something about the request. Silly example:
    if (request.headers['content-type'] === 'application/x-www-form-urlencoded') {
        // and now you can add things to the headers, querystring, etc.
        request.headers.apiKey = apiKey;
    }
    next();
  };
};

// use 'abc123' for API key middleware
// listen on port 8000
// forward the requests to 192.168.0.12 on port 3000
httpProxy.createServer(apiKeyMiddleware('abc123'), 3000, '192.168.0.12').listen(8000);

See Node-HTTP-Proxy, Middlewares, and You for more detail and also some cautions on the approach.

explunit
  • 18,967
  • 6
  • 69
  • 94
  • Steve, thanks! It def make sense in terms of headers. Are there any solutions for tweaking request data/body itself, like adding API token? – aliona Dec 18 '12 at 19:55
  • @aliona I think you can modify it just like above with request.body, but perhaps you can tell us how API key is expected to be received in the API you're using. Generally I would have expected it to be in either querystring or headers. – explunit Dec 18 '12 at 20:47
  • API expects api token to be present in either querystring or request body depending on request method `GET`, `POST`, `UPDATE` or `DELETE` – aliona Dec 20 '12 at 19:14
  • @aliona so your issue is a) figuring out how to switch between putting it in the body vs. querystring based on method or b) how to append to the request body? – explunit Dec 20 '12 at 19:43
  • My issue is mostly related to A. I was just wondering whether `node-http-proxy` can help me to do it easily at some point, so that I can stop doing it "manually". Currently my steps are as follows : 1) find out request method; 2) get request data by either parsing querystring or collecting request body, depending on method; 3) add needed headers and tweak request data if needed; 4) proxy request to API – aliona Dec 25 '12 at 15:11