user1250991
user1250991

Reputation: 97

Accessing req.body values in express

I'm working on a REST API node/express app. For my 'signup' route, where a user uses the api to sign up for the service, it takes a POST'ed JSON object. Inside this function I want to check against the mongo db to make sure that this user doesn't already exist.

The problem is I need to get the username from the posted json information, but every attempt I have made has failed. The lines that attempt to log the req.body.username and req.body.password always return 'undefined'. What am I doing wrong?

Here's the code I have so far is below:

exports.signup = function(req, res) {

  // todo: somehow verify that username, password, email and phone number are all provided.
  // do not write into the collection unless we know all the information has been provided.
  // maybe access the JSON elements to make sure they are not null
  // todo: also make sure a record doesn't already exist for this uer

  var user = req.body;

  // need to get the username here somehow
  var JSONuser = JSON.stringify(user);
 // console.log('user: ' + user);
  console.log('userJSON: ' + JSON.stringify(user));
  console.log('username: ' + req.body.username);
  console.log('password: ' + req.body.password);

  db.collection('users', function(err, collection){
    //if ( collection.findOne({}) ) { // make sure the user doesn't already exist here
        collection.insert(user, {safe:true}, function(err, result){
          if(err){
            res.send({'error':'An error has occured'});
          } else {
            console.log('Success: ' + JSON.stringify(result[0]));
            res.send(result[0]);
          }
        })
    //}
  });
}

Upvotes: 0

Views: 5179

Answers (1)

Matt Greenberg
Matt Greenberg

Reputation: 2330

By default in express, you don't have access to those variables through dot syntax. You would have to parse the response. Luckily, we have a package for that.

Use body-parser middle ware for easy access to post variables.

// install it
bash$: npm install body-parser    

// require it in your project
bodyParser = require('body-parser');

// `use` it in your express app
app.use(bodyParser.urlencoded({ extended: true}));

// now you your post values are available on the req.body.postVariableName

I use this in almost all of my projects, it just makes it easy.

* EDIT *

I looked at your repo and everything actually looks fine as it pertains the reading of parsed values; however, they way you are console logging them may be where you are getting confused. I rewrote your signin route so I could explain better.

exports.signin = function(req, res) {

    var user = req.body;
    console.log('req.body: ' + JSON.stringify(user));
    console.log('Signing In As User: ' + user.username);
    console.log('Password: ' + user.password);
    res.send('You just signed in!');

}

I tested this my opening up another terminal and curling a JSON post.

curl -H "Content-Type: application/json" -X POST -d '{"username":"testuser","password":"testpassword"}' http://localhost:3000/signin

As you can see it should work.

Some things worth mentioning. When you wrote console.log('req.body: ' + req.body);. You are not going to see the data you want. You are going to see req.body: [object] in the output because javascript is going to render this as req.body.toString() which is just the identifier. If you want to post the code, use JSON.stringify(req.body) or use console.dir(req.body).

Second, req.body will just give u access the body object.

// this is just user.toString() which is again [object]
console.log('Signing In As User: ' + user);

// You need to use the dot syntax to get user.username
console.log('Signing In As: " + user.username);

If you are stilling seeing issues, its because of the way you are making posts localhost, not because of your code.

Upvotes: 1

Related Questions