mirror of
https://github.com/http-party/node-http-proxy.git
synced 2025-12-08 20:59:18 +00:00
[examples] Restream body before proxying, support for Content-Type of application/x-www-form-urlencoded (#1264)
This commit is contained in:
parent
42e8e1e099
commit
a3fe02d651
@ -29,6 +29,7 @@ var http = require('http'),
|
|||||||
request = require('request'),
|
request = require('request'),
|
||||||
colors = require('colors'),
|
colors = require('colors'),
|
||||||
util = require('util'),
|
util = require('util'),
|
||||||
|
queryString = require('querystring'),
|
||||||
bodyParser = require('body-parser'),
|
bodyParser = require('body-parser'),
|
||||||
httpProxy = require('../../lib/http-proxy'),
|
httpProxy = require('../../lib/http-proxy'),
|
||||||
proxy = httpProxy.createProxyServer({});
|
proxy = httpProxy.createProxyServer({});
|
||||||
@ -36,12 +37,23 @@ var http = require('http'),
|
|||||||
|
|
||||||
//restream parsed body before proxying
|
//restream parsed body before proxying
|
||||||
proxy.on('proxyReq', function(proxyReq, req, res, options) {
|
proxy.on('proxyReq', function(proxyReq, req, res, options) {
|
||||||
if(req.body) {
|
if (!req.body || !Object.keys(req.body).length) {
|
||||||
let bodyData = JSON.stringify(req.body);
|
return;
|
||||||
// incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
|
}
|
||||||
proxyReq.setHeader('Content-Type','application/json');
|
|
||||||
|
var contentType = proxyReq.getHeader('Content-Type');
|
||||||
|
var bodyData;
|
||||||
|
|
||||||
|
if (contentType === 'application/json') {
|
||||||
|
bodyData = JSON.stringify(req.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (contentType === 'application/x-www-form-urlencoded') {
|
||||||
|
bodyData = queryString.stringify(req.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bodyData) {
|
||||||
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
|
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
|
||||||
// stream the content
|
|
||||||
proxyReq.write(bodyData);
|
proxyReq.write(bodyData);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -94,5 +106,3 @@ http.createServer(app1).listen(9013, function(){
|
|||||||
console.log('return for urlencoded request:' ,err, data)
|
console.log('return for urlencoded request:' ,err, data)
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user