Skip to content

Commit a3fe02d

Browse files
renxiajcrugzz
authored andcommitted
[examples] Restream body before proxying, support for Content-Type of application/x-www-form-urlencoded (#1264)
1 parent 42e8e1e commit a3fe02d

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

examples/middleware/bodyDecoder-middleware.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,19 +29,31 @@ var http = require('http'),
2929
request = require('request'),
3030
colors = require('colors'),
3131
util = require('util'),
32+
queryString = require('querystring'),
3233
bodyParser = require('body-parser'),
3334
httpProxy = require('../../lib/http-proxy'),
3435
proxy = httpProxy.createProxyServer({});
3536

3637

3738
//restream parsed body before proxying
3839
proxy.on('proxyReq', function(proxyReq, req, res, options) {
39-
if(req.body) {
40-
let bodyData = JSON.stringify(req.body);
41-
// incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
42-
proxyReq.setHeader('Content-Type','application/json');
40+
if (!req.body || !Object.keys(req.body).length) {
41+
return;
42+
}
43+
44+
var contentType = proxyReq.getHeader('Content-Type');
45+
var bodyData;
46+
47+
if (contentType === 'application/json') {
48+
bodyData = JSON.stringify(req.body);
49+
}
50+
51+
if (contentType === 'application/x-www-form-urlencoded') {
52+
bodyData = queryString.stringify(req.body);
53+
}
54+
55+
if (bodyData) {
4356
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
44-
// stream the content
4557
proxyReq.write(bodyData);
4658
}
4759
});
@@ -94,5 +106,3 @@ http.createServer(app1).listen(9013, function(){
94106
console.log('return for urlencoded request:' ,err, data)
95107
})
96108
});
97-
98-

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy