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!
body is empty, it returns an empty object, as such, making ! req. body return false even when it's empty. Instead, you should test for !
Body-parser is the Node. js body parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it.
bodyParser. json returns middleware that only parses JSON. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings. A new body object containing the parsed data is populated on the request object after the middleware (i.e. req. body ).
The req. body object allows you to access data in a string or JSON object from the client side. You generally use the req. body object to receive data through POST and PUT requests in the Express server.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With