24

I was working on a simple API using Node.JS and Restify tonight and had everything fine in terms of receiving parameters via req.params.fieldname. I installed CouchDB and Cradle in order to start trying to throw those parameters into a database, but after getting everything installed req.params started to come back empty!

I should have been using Express to begin with for other reasons, so I tried switching to that to see if I could get it working but no such luck.

var express = require('express');
var app = express.createServer();

app.configure(function(){
app.use(express.bodyParser());
app.use(express.cookieParser());
});

app.post('/', function(req, res){
  res.send(req.body);
});

app.listen(8080, function() {
  console.log('Printomatic listening at', app.url);
});

I've tried countless variations but no matter what req.body comes back empty. I'm using http-console to test, and sending things as simple as POST / with content {"name":"foobar"}

I'm so frustrated that at this point I'm beginning to wonder if I broke something when installing Cradle/CouchDB (which were installed with NPM and Homebrew, respectively). Any help would be greatly appreciated as this is somewhat time-sensitive. Thanks for any help in advance!

Matt McClure
  • 2,046
  • 2
  • 18
  • 19
  • what happens if you try app.get('/', function(req,res){res.send('Hello World');}; and then do a get request?? – bryanmac Mar 28 '12 at 05:28

1 Answers1

72

You mention that you post JSON data ({"name": "foobar"}). Make sure that you send Content-Type: application/json with that, or bodyParser will not parse it.

E.g.:

$ curl -d 'user[name]=tj' http://local/
$ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/

This is because bodyParser parses application/json, application/x-www-form-encoded and multipart/form-data, and it selects which parser to use based on the Content-Type.

moffeltje
  • 4,521
  • 4
  • 33
  • 57
Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
  • 4
    I feel like an idiot. I was using http-console and I guess for some reason the headers changed! Thank you! – Matt McClure Mar 28 '12 at 22:44
  • 2
    I was using Postman REST client and it worked when I used form-data but not when sending raw. Setting content type in the header fixed it. Thanks – Nikhil Baliga Feb 01 '14 at 07:41
  • 1
    Thank you Nikhil! I had the same issue with Postman, and we have to set the header: Content-Type (no colon) and Value: application/json – Zack S Mar 09 '15 at 20:03
  • Saved me a lot of time and punches :). Thanks! – nish Aug 16 '15 at 18:19