Node.js代理能够更改响应头并注入其他请求数据

时间:2012-12-07 14:43:30

标签: api node.js node-http-proxy

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

我想使用node-http-proxy,我已找到a way to modify response headers

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

或许我搞砸了node-http-proxy的目的并且有更适合我的目的?

1 个答案:

答案 0 :(得分:3)

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

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, and You以及该方法的一些注意事项。