Node.js代理能够更改响应头并注入额外的请求数据

我正在编写一个node.js代理服务器,向不同域中的API提供请求。

我想使用节点HTTP代理 ,我已经find了一种方法来修改响应头 。

但有没有办法修改条件(即添加API密钥)的请求数据,并考虑到可能有不同的方法请求 – GETPOSTUPDATEDELETE

或者,也许我搞乱了node-http-proxy的目的,有什么更适合我的目的?

一种简单的方法是使用中间件。

 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); 

请参阅Node-HTTP-Proxy,Middlewares和You ,了解更多细节以及该方法的一些注意事项。