0

I am writing the backend of a simple app using node and express. This is how I have structured my code:

app.js

var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());
var router = require('./router')(app);

app.listen(80,function(){
    console.log("Started on PORT 80");
})
module.exports = app;

Under subdirectory /router I have index.js

module.exports = function (app) {
    app.use('/login', require('./routes/login'));
};

Under /router/routes I have login.js

var express = require('express');
var router = express.Router();
router.post('/', function(req, res){
    var user = req.body.user;
    console.log("Handler for /login called");
    console.log("The username is: "+ user);
});
module.exports = router;

I am testing using

curl -X POST -d '{"user":"alpha", "password":"beta"}' http:my-app-ip/login --header "Content-Type:application/json"

The console prints The username is: undefined instead of the value for key user.

What am i doing wrong?

mahdt
  • 51
  • 4
  • Did you try moving all of the cURL options *before* the URL? I'm wondering if the header isn't being set ... – mscdex May 19 '15 at 07:25

2 Answers2

1

You can use util.inspect() to get a string representation of the value, or use console.dir(req.body) which outputs util.inspect(req.body) to stdout.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • console.dir worked. It now prints { user: 'alpha', password: 'beta} So the app is getting the correct text. But the body parser still doesnt work. I have modified the code to add the lines var user = req.body.user; console.log(user) but it prints undefined – mahdt May 19 '15 at 06:53
  • I have edited my original question to reflect the code changes and the current output. When I had the same code all in one file, it worked fine. But when I split it like this the body parser stopped working. – mahdt May 19 '15 at 07:01
0

You are doing nothing wrong. The [Object object] you see is due to the console.log.

Try this: console.log(req.body.user). My guess is that you'll see the correct output.

Have a look to this question though

Community
  • 1
  • 1
javierfdezg
  • 2,087
  • 1
  • 22
  • 31