我正在尝试使用 node-http-proxy 作为反向代理,但我似乎无法让 POST 和 PUT 请求工作。文件 server1.js 是反向代理(至少对于带有 url “/forward-this”的请求),server2.js 是接收代理请求的服务器。请解释我做错了什么。
这是 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();
}