From 35fb4bb47a743761cc8be0c5e42e6b790b4f899b Mon Sep 17 00:00:00 2001 From: Nick O'Leary Date: Wed, 12 Feb 2014 21:30:49 +0000 Subject: [PATCH] Add rawBody middleware Fixes #151 --- nodes/core/io/21-httpin.js | 31 +++++++++++++++++++++++++++---- package.json | 1 + 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/nodes/core/io/21-httpin.js b/nodes/core/io/21-httpin.js index 54c2b6f28..5af17fbb7 100644 --- a/nodes/core/io/21-httpin.js +++ b/nodes/core/io/21-httpin.js @@ -20,28 +20,51 @@ var http = require("follow-redirects").http; var https = require("follow-redirects").https; var urllib = require("url"); var express = require("express"); +var getBody = require('raw-body'); var jsonParser = express.json(); var urlencParser = express.urlencoded(); +function rawBodyParser(req, res, next) { + if (req._body) return next(); + req.body = ""; + req._body = true; + getBody(req, { + limit: '1mb', + length: req.headers['content-length'], + encoding: 'utf8' + }, function (err, buf) { + if (err) return next(err); + req.body = buf; + next(); + }); +} + + function HTTPIn(n) { RED.nodes.createNode(this,n); this.url = n.url; this.method = n.method; var node = this; + + this.errorHandler = function(err,req,res,next) { + node.warn(err); + res.send(500); + }; + this.callback = function(req,res) { if (node.method == "post") { node.send({req:req,res:res,payload:req.body}); } else if (node.method == "get") { node.send({req:req,res:res,payload:req.query}); } else node.send({req:req,res:res}); } if (this.method == "get") { - RED.app.get(this.url,this.callback); + RED.app.get(this.url,this.callback,errorHandler); } else if (this.method == "post") { - RED.app.post(this.url,jsonParser,urlencParser,this.callback); + RED.app.post(this.url,jsonParser,urlencParser,rawBodyParser,this.callback,this.errorHandler); } else if (this.method == "put") { - RED.app.put(this.url,jsonParser,urlencParser,this.callback); + RED.app.put(this.url,jsonParser,urlencParser,rawBodyParser,this.callback,this.errorHandler); } else if (this.method == "delete") { - RED.app.delete(this.url,this.callback); + RED.app.delete(this.url,this.callback,errorHandler); } this.on("close",function() { diff --git a/package.json b/package.json index 7eab6fd12..26f7e006f 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "clone": "~0.1.11", "mustache": "~0.7.2", "cron":"1.x", + "raw-body":"~1.1.2", "twitter-ng":"~0.6.2", "oauth":"~0.9.10", "xml2js":"~0.2.8",