Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix] bodyparser example - support for Content-Type of application/x-www-form-urlencoded #1264

Merged
merged 1 commit into from Jun 6, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 17 additions & 7 deletions examples/middleware/bodyDecoder-middleware.js
Expand Up @@ -29,19 +29,31 @@ var http = require('http'),
request = require('request'),
colors = require('colors'),
util = require('util'),
queryString = require('querystring'),
bodyParser = require('body-parser'),
httpProxy = require('../../lib/http-proxy'),
proxy = httpProxy.createProxyServer({});


//restream parsed body before proxying
proxy.on('proxyReq', function(proxyReq, req, res, options) {
if(req.body) {
let bodyData = JSON.stringify(req.body);
// incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
proxyReq.setHeader('Content-Type','application/json');
if (!req.body || !Object.keys(req.body).length) {
return;
}

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));
// stream the content
proxyReq.write(bodyData);
}
});
Expand Down Expand Up @@ -94,5 +106,3 @@ http.createServer(app1).listen(9013, function(){
console.log('return for urlencoded request:' ,err, data)
})
});