javascript - Why am I getting [object object ] instead of JSON? - Stack Overflow

I'm making an API. When I send correct data for login, I get JSON but when I send incorrect data,

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
          })
        }
      });
  });

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
          })
        }
      });
  });
Share Improve this question edited Oct 18, 2019 at 6:26 VladNeacsu 1,28816 silver badges33 bronze badges asked Oct 18, 2019 at 6:06 Budhathoki1998Budhathoki1998 1251 gold badge2 silver badges7 bronze badges 3
  • getting [Object object] only by sending incorrect data? – Sudhakar Commented Oct 18, 2019 at 6:09
  • UserModel.findOne({ username: req.body.username, }) is failing to find the username from DB and you are not catching or returning any response for that. That may be the reason – Yahiya Commented Oct 18, 2019 at 6:10
  • [Object object] means you have received an object. The value of type usually returned when you either concatinate the object with string. – James Commented Oct 18, 2019 at 6:31
Add a ment  | 

3 Answers 3

Reset to default 5

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}

 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.

You can do this without using next. Try this code, It will work straight away!

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) {
              console.log(err);
              res.status(500).json({message:'Backend error'})
            }
            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,
                  message:'Login successful'
                });
              } else {
                res.status(400).json({message:'Wrong password'})
              }
            } else {
              res.status(400).json({message:'User does not exist'})
            }
          });
      });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744258323a4565504.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信