How to reverse proxy client POST & PUT requests using node-http-proxy

I'm trying to use the node-http-proxy as a reverse proxy, but I can't seem to get POST and PUT requests to work. The file server1.js is the reverse proxy (at least for requests with the url "/forward-this") and server2.js is the server that receives the proxied requests. Please explain what I'm doing incorrectly. Here's the code for 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(); } } And here's the code for 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(); }

以上就是How to reverse proxy client POST & PUT requests using node-http-proxy的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » Node.js答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏