我正在编写一个node.js代理服务器,将请求提供给不同域上的API。
我想使用node-http-proxy,并且我已经找到a way to modify response headers。
但是有没有一种方法可以根据条件(即添加API key )修改请求数据,并考虑到可能有不同的方法request-GET
,POST
,UPDATE
,DELETE
?
还是我搞砸了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, and You,以及有关此方法的一些注意事项。
关于api - Node.js代理具有更改响应头和注入(inject)其他请求数据的能力,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13765304/