2

I'm trying to get the post variables in a little service I wrote but cannot seem to get it out of the request variable in my app.post method. I believe it's some way that I'm processing the request. Are there additional steps I must take to process the request? I've also tried using express.bodyParser() but I got an error saying that this is deprecated. The following is my little node.js file:

        var express = require('express');
        var app = express();
        app.use(express.json());
        // posting method : curl -X POST http://localhost:8080/post-page -d name=ArrowKneeous
        // to look at the req I found it better to start using: 
        // nohup node testPost.js > output.log &
        app.post('/post-page',function(req,res){
        var name= req.body.name;
        //undefined
        console.log('name is :' + name);
        //object
         console.log('req is: '+req);
        //object
        console.log('req.body is: ' +req.body);
        //undefined
        console.log('req.body.name is: '+req.body.name);
        //undefined
         console.log('req.params[0]: '+req.params[0]);
         //undefined
         console.log('req.query.name is: '+req.query.name);
         //empty brackets
         console.dir(req.body);
         //huge
         console.dir(req);
         //got stuff is replied to the curl command
         res.send('got stuff');
       });
    app.listen(8080);
ArrowKneeous
  • 97
  • 1
  • 3
  • 8

1 Answers1

3

You have

app.use(express.json());

to process a JSON post, but are POSTing standard URL encoded form data.

-d name=ArrowKneeous

You either need to post JSON

-d '{"name": "ArrowKneeous"}' -H "Content-Type: application/json"

or you need to tell express to also accept URL encoded POST data.

app.use(express.urlencoded());

Edit

This applies to Express 3.x. It should be almost the same with 4.x, but you will need to load the body-parser module instead:

var bodyParser = require('body-parser');

app.use(bodyParser.json());
// OR
app.use(bodyParser.urlencoded());
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 1
    Great answer, @loganfsmyth. Most people would just say `app.use(express.bodyParser())`, but I prefer to use `json` or `urlencoded` directly since `multipart` (currently included in `bodyParser`) will be deprecated soon. – Ethan Brown Jan 08 '14 at 20:16
  • 1
    I'm getting an error when I;m trying to use suggested solution : Error: Most middleware (like json) is no longer bundled with Express and must be installed separately – Igal Jun 18 '14 at 06:20
  • 1
    @Igal Updated. Keep in mind that Express has a new major version (`4.x`), so any answer older than a month or so may not be accurate. – loganfsmyth Jun 18 '14 at 14:31