Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting [object object ] instead of JSON?

I'm making an API. When I send correct data for login, I get JSON but when I send incorrect data, I get this [object object] message, why?

When the correct information is provided.

Here is my code.

router.route('/login').post(function (req, res, next) {
    console.log('i should be here when path match to login', req.body);

    UserModel.findOne({
        username: req.body.username,
      })
      .exec(function (err, user) {
        if (err) {
          return next(err);
        }
        if (user) {
          var passwordMatch = passwordHash.verify(req.body.password, user.password);
          if (passwordMatch) {
            var token = generateToken(user);
            res.status(200).json({
              user: user,
              token: token
            });
          } else {
            next({
              message: "password didnot match",
              status: 400
            })
          }
        } else {
          next({
            message: 'Invalid Username',
            status: 400
          })
        }
      });
  });
like image 790
Budhathoki1998 Avatar asked Sep 06 '25 03:09

Budhathoki1998


2 Answers

The value [Object object] has nothing to do with the data you sent. This has to do with the way you print the value.

[Object object] means you have received an object. The value of type usually returned when you either concatinate the object with string.

Example:

var obj = {a: 1};
console.log('Printing ' + obj); // Prints [object object]

So, instead of concatinating the object, you can stringify the object and print it.

Example

var obj = {a: 1};
console.log('Printing ' + JSON.stringify(obj)); // Prints {"a":1}

Or

var obj = {a: 1};
console.log('Printing ', obj); // Prints formatted {"a":1}
like image 62
James Avatar answered Sep 07 '25 20:09

James


 res.status(200).json({
              user: user,
              token: token
            });

This is how you are sending on success. You are formatting response as JSON. But on failure, you are returning plain JS Object. Formatting failure responses as JSON object will solve your problem.

like image 25
rachanna Avatar answered Sep 07 '25 21:09

rachanna