Tôi đang cố gắng sử dụng nút-http-proxy làm proxy ngược, nhưng dường như tôi không nhận được yêu cầu POST và PUT để hoạt động. Tệp server1.js là proxy ngược (ít nhất là đối với các yêu cầu có url "/ forward-this") và server2.js là máy chủ nhận các yêu cầu proxy. Hãy giải thích những gì tôi đang làm không chính xác.Cách đảo ngược yêu cầu POST & PUT của máy khách proxy bằng cách sử dụng nút-http-proxy
Dưới đây là các mã cho 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();
}
}
Và đây là mã cho 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();
}
Điều đó hoạt động hoàn hảo. Cảm ơn! –
Mặc dù, nó là một câu trả lời cũ, để làm cho nó hoạt động, bạn nên thay thế 'var proxy = new httpProxy.RoutingProxy(); ' với' var proxy = httpProxy.createProxyServer ({}); ' – Saber