首页 > 解决方案 > 创建登录时,到达一个空对象

问题描述

空对象来登录。使用注册,在登录的相似性中完成,所以一切正常。通过 Postman 发送请求,您可以注册一个用户并检查该用户是否存在于数据库中。当您发送登录请求而不是令牌时,一条消息来自最后一个块“else”“未找到具有此类电子邮件地址的用户”。

      const bcrypt = require('bcryptjs');
      const jwt = require('jsonwebtoken');
      const User = require('../models/User');
      const keys = require('../config/keys');

      module.exports.login = async function (req, res) {
      console.log('req.body', req.body);   //Empty object {}
      const candidate = await User.findOne({
      email: req.body.email
      });
      if (candidate) {
      const passwordResult = bcrypt.compareSync(req.body.password, 
      candidate.password);

      if (passwordResult) {
        const token = jwt.sign({
            email: candidate.email,
            userId: candidate._id
        }, keys.jwt, {expiresIn: 60 * 60});

        res.status(200).json({
            token: `Bearer ${token}`
        })
      } else {
        res.status(401).json({
            message: 'Passwords do not match'
        })
      }
      } else {
           console.log(req.body.email);
           console.log(candidate);
        res.status(404).json({
            message: 'User with such email address not found'
       })
       }
       };

       module.exports.register = async function (req, res) {
           console.log('req.body', req.body);
           const candidate = await User.findOne({
           email: req.body.email
       });
       if (candidate) {
       res.status(409).json({
          message: "User with this email address already exists"
       })
       } else {
          const salt = bcrypt.genSaltSync(10);
          const password = req.body.password;
          const user = new User({
              email: req.body.email,
              password: bcrypt.hashSync(password, salt)
       });
          try {
              await user.save();
              res.status(201).json(user)
       } catch (e) {
       }
       }
       };

![注册正常] ( https://imgur.com/a/9T5vRMD )

!【无法正常登录】(https://imgur.com/a/rQOiw2w)“一定是token,因为这个用户已经存在”

标签: javascriptnode.js

解决方案


我自己找到了答案。我使用“x-form-urlencoded”,登录工作正常,我得到一个有效的令牌。显然问题出在 Postman 的内部实现中,因为借助“rav”输入的数据也应该是有效的。


推荐阅读