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

0

3 Answers 3

3

Assuming you're trying req.body.text,

Have you used bodyParser?

app.use(express.bodyParser());
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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 and API reference are a good place to start.
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());

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.