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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With