我試圖使用node-http-proxy作爲反向代理,但似乎無法使POST和PUT請求正常工作。文件server1.js是反向代理(至少對於具有url「/ forward-this」的請求),server2.js是接收代理請求的服務器。請解釋我做錯了什麼。如何使用node-http-proxy反向代理客戶端POST&PUT請求
下面是server1.js代碼:
// File: server1.js
//
var http = require('http');
var httpProxy = require('http-proxy');
httpProxy.createServer(function (req, res, proxy) {
if (req.method == 'POST' || req.method == 'PUT') {
req.body = '';
req.addListener('data', function(chunk) {
req.body += chunk;
});
req.addListener('end', function() {
processRequest(req, res, proxy);
});
} else {
processRequest(req, res, proxy);
}
}).listen(8080);
function processRequest(req, res, proxy) {
if (req.url == '/forward-this') {
console.log(req.method + ": " + req.url + "=> I'm going to forward this.");
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 8855
});
} else {
console.log(req.method + ": " + req.url + "=> I'm handling this.");
res.writeHead(200, { "Content-Type": "text/plain" });
res.write("Server #1 responding to " + req.method + ": " + req.url + "\n");
res.end();
}
}
這裏是爲server2.js代碼:
// File: server2.js
//
var http = require('http');
http.createServer(function (req, res, proxy) {
if (req.method == 'POST' || req.method == 'PUT') {
req.body = '';
req.addListener('data', function(chunk) {
req.body += chunk;
});
req.addListener('end', function() {
processRequest(req, res);
});
} else {
processRequest(req, res);
}
}).listen(8855);
function processRequest(req, res) {
console.log(req.method + ": " + req.url + "=> I'm handling this.");
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write("Server #2 responding to " + req.method + ': url=' + req.url + '\n');
res.end();
}
完美的工作。謝謝! – 2013-02-28 17:01:40
儘管這是一箇舊的答案,但要使其發揮作用,您應該使用'var proxy = httpProxy.createProxyServer({});'var proxy = new httpProxy.RoutingProxy();' ; – Saber 2017-08-18 19:54:13