5

I'm trying to simulate a POST request to a server app based in Express for nodeJS. It's running on localhost:3000 (JS Fiddle: http://jsfiddle.net/63SC7/)

I use the following CURL line:

 curl -X POST -d "{\"name\": \"Jack\", \"text\": \"HULLO\"}" -H "Content-Type: application/json" http://localhost:3000/api 

but get the error message:

Cannot read property 'text' of undefined

Any ideas what I'm doing wrong?

Note: I can make a successful GET request using this line:

curl http://localhost:3000/api

user3281031
  • 57
  • 1
  • 1
  • 4

3 Answers3

3

Assuming you're trying req.body.text,

Have you used bodyParser?

app.use(express.bodyParser());
josh3736
  • 139,160
  • 33
  • 216
  • 263
  • That worked great thanks! Do I need to add this line to the server code whenever I want to work with POST data? Don't suppose you know of a good online resource to learn a bit more about this? – user3281031 Mar 02 '14 at 16:03
  • The `bodyParser` is optional middleware. By default, Express doesn't parse request bodies. So yes, you need to `use` the `bodyParser` (once per app), or you can include it in an individual route's middleware chain if you don't want/need to parse request bodies for every request. To learn more, the Express [guide](http://expressjs.com/guide.html) and [API reference](http://expressjs.com/3x/api.html) are a good place to start. – josh3736 Mar 02 '14 at 18:33
2

The answer by josh3736 is outdated. Express no longer ships with the body-parser middleware. To use it you must install it first:

npm install --save body-parser

Then require and use:

let bodyParser = require('body-parser');
app.use(bodyParser());
thordarson
  • 5,943
  • 2
  • 17
  • 36
2

Just to update Thordarson's answer (which is now deprecated), the currently recommended way is:

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

See also https://stackoverflow.com/a/24330353/3810493

Christian Z.
  • 361
  • 4
  • 6