I'm building my first node.js site with expressjs.
Part of it is handling notifications from Fitbit to an endpoint on my site, /api/1/fitbit_update
, like this one:
POST /api/1/fitbit_update HTTP/1.1
Host: myhost.dk
Content-Type: multipart/form-data; boundary=JGUOAeGT3Fjgjcdk6s35F2mPVVyTdzgR
Content-Length: 374
Connection: keep-alive
--JGUOAeGT3Fjgjcdk6s35F2mPVVyTdzgR
Content-Disposition: form-data; name="updates"; filename="update1353963418000.json"
Content-Type: application/json; charset=UTF-8
Content-Transfer-Encoding: binary
[{"collectionType":"activities","date":"2012-11-26","ownerId":"qw12er23","ownerType":"user","subscriptionId":"112233-activities"}]
--JGUOAeGT3Fjgjcdk6s35F2mPVVyTdzgR--
I need to parse the json object in the body of the HTTP request, but Express cannot help me with that.
Any ideas how to get a hold of the JSON object?
I've seen some middleware examples, but I'm not sure how to actually get to the contents with the req.on('someevent') approach.
req.body
returns an empty object {}
So this request is a multipart file upload where the file you are interested in is a JSON document. Check out the express multipart example. You will want to do something like:
req.files.updates.path
JSON.parse
Try req.body
in your POST route handler.
Add express.bodyParser()
for older version:
app.express.createServer(
express.cookieParser(),
express.bodyParser(),
.....
);
for newer version:
server.use(express.bodyParser());
Then you can access body by using req.body
Values sent from form using post method: email and password
app.post('/login', function(req, res){
/* Get Errors of Validates */
var errors = [];
req.onValidationError(function(msg) {
errors.push(msg);
//console.log('msg: ' + msg);
return this;
});
/* Validates */
req.sanitize('email').xss();
req.sanitize('password').xss();
req.assert('email', 'Range email').len(6, 40);
req.assert('password', 'Range password').len(6, 20);
//*****************************************************
// Value Send Post "password" --> req.body.password
//*****************************************************
var pass_shasum = crypto.createHash('sha256').update(req.body.password).digest('hex');
....
Regards.