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



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

我想使用 node-http-proxy 并且我已经找到了一种修改响应标头的方法。

但是有没有办法在条件下修改请求数据(即添加 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 和 U,了解更多详细信息以及有关该方法的一些注意事项。

最新更新