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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 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.
API expects api token to be present in either querystring or request body depending on request method GET, POST, UPDATE or DELETE
@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?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.