Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node (Express) request body empty

Tags:

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!

like image 956
Matt McClure Avatar asked Mar 28 '12 05:03

Matt McClure


People also ask

How do I check if a REQ is empty in node?

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 !

Why we use bodyParser in node js?

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.

What is bodyParser json()?

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 ).

What is req body in express?

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.


1 Answers

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.

like image 107
Linus Thiel Avatar answered Oct 14 '22 16:10

Linus Thiel