Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 361
aliona Avatar asked Dec 07 '12 14:12

aliona


1 Answers

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.

like image 97
explunit Avatar answered Sep 28 '22 17:09

explunit