Mix Austria
Mix Austria

Reputation: 935

Request body has value but I can't access it

I am currently doing some user signup from angular2 front end to express back end. Everything is working fine except on getting the values from the request body. Take a look at this.

usersRoute.js

userRouter.route('/signup')
    .post(function(req, res){
      console.log(req.body);
      mongoose.connect(url, function(err){
        var user = {
          username: req.body.username,
          password: req.body.password,
          firstname: req.body.firstname,
          lastname: req.body.lastname,
          gender: req.body.gender,
          address: req.body.address,
          contact: req.body.contact,
          email: req.body.email
        };
        console.log(user);
        users.create(user, function(err, results){
          // res.redirect('http://localhost:4200/login');

          //tobeChanged
          console.log(results);
          mongoose.disconnect();
        });
      });
    });

On the first console.log I am trying to look if there is a value on the req.body and then on the second console.log is when I am trying to see if the user variable got some value. This is what happens.

enter image description here

as we can see, user variable has no value but I am accessing it through req.body.name. Can someone help me clarify this?

OPTIONAL QUESTION: Those \n is bothering me. How to get rid of it?

Upvotes: 4

Views: 1984

Answers (3)

Binit Ghetiya
Binit Ghetiya

Reputation: 1979

Problem:

Here your request object's scope is different. you want to use request object in function callback.

So one thing you can do is passing that value which calling callback.

Solution: Change this

mongoose.connect(url, function(err){

To this

mongoose.connect(url, function(err,req){

Hope this will help.Thanks

Upvotes: 1

Elson D'souza
Elson D'souza

Reputation: 95

You need to use some library like body-parser to do this. The fix would be adding the following lines of code:

var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });

and change the first two lines of your code as the following:

userRouter.route('/signup')
.post(urlencodedParser,function(req, res){

The reason for this is the body of the http post request is not extracted by express and hence another library like body-parser is required to perform the task.

Upvotes: 0

Hank Phung
Hank Phung

Reputation: 2149

You can try declare the user object outside of the callback.

.post(function(req, res){
  console.log(req.body);
  var user = {
      username: req.body.username,
      password: req.body.password,
      firstname: req.body.firstname,
      lastname: req.body.lastname,
      gender: req.body.gender,
      address: req.body.address,
      contact: req.body.contact,
      email: req.body.email
    };
    mongoose.connect(url, function(err){...

If it not work, you can use bind to bring the data in.

Upvotes: 0

Related Questions