user3281031
user3281031

Reputation: 57

curl with nodejs express - POST data

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

Upvotes: 5

Views: 13821

Answers (3)

Christian Z.
Christian Z.

Reputation: 441

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

Upvotes: 2

thordarson
thordarson

Reputation: 6251

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());

Upvotes: 2

josh3736
josh3736

Reputation: 144912

Assuming you're trying req.body.text,

Have you used bodyParser?

app.use(express.bodyParser());

Upvotes: 3

Related Questions