Node.js proxy with ability to change response headers and inject additional request data
Asked Answered
T

1

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?

Tonneau answered 7/12, 2012 at 14:43 Comment(0)
W
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.

Wordage answered 14/12, 2012 at 18:53 Comment(5)
Steve, thanks! It def make sense in terms of headers. Are there any solutions for tweaking request data/body itself, like adding API token?Tonneau
@Tonneau 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.Wordage
API expects api token to be present in either querystring or request body depending on request method GET, POST, UPDATE or DELETETonneau
@Tonneau 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?Wordage
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 APITonneau

© 2022 - 2024 — McMap. All rights reserved.