mysql 未处理的拒绝错误:WHERE参数“number_phone”具有无效的“undefined”值

mtb9vblg  于 2024-01-05  发布在  Mysql
关注(0)|答案(2)|浏览(104)

我用reactjs和express js和sequilize做了一个登录应用程序,当我用postman API测试时,一切都正常,但当我用reactjs测试时,它在后端给了我给予这个问题

model/user.model.js

后台代码

module.exports = (sequelize, Sequelize) => {
  const User = sequelize.define('users', {
    name: {
      type: Sequelize.STRING
    },
    number_phone: {
      type: Sequelize.INTEGER
    },
    password: {
      type: Sequelize.STRING
    }
  });

  return User;
}

字符串

router/verifySignUp.js

后台代码

const db = require('../config/db.config.js');
const config = require('../config/config.js');
const ROLEs = config.ROLEs; 
const User = db.user;
const Role = db.role;

checkDuplicatePhone = (req, res, next) => {
  // -> Check Username is already in use
  User.findOne({
    where: {
      number_phone: req.body.number_phone
    } 
  }).then(user => {
    if(user){
      res.status(400).send("Fail -> Phone is already taken!");
      return;
    }
      next();
  });
}

checkRolesExisted = (req, res, next) => {  
  for(let i=0; i<req.body.roles.length; i++){
    if(!ROLEs.includes(req.body.roles[i].toUpperCase())){
      res.status(400).send("Fail -> Does NOT exist Role = " + req.body.roles[i]);
      return;
    }
  }
  next();
}

const signUpVerify = {};
signUpVerify.checkDuplicatePhone = checkDuplicatePhone;
signUpVerify.checkRolesExisted = checkRolesExisted;

module.exports = signUpVerify;

controller/controller.js

后台代码

const db = require('../config/db.config.js');
const config = require('../config/config.js');
const User = db.user;
const Role = db.role;

const Op = db.Sequelize.Op;

var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');

exports.signup = (req, res) => {
    // Save User to Database
    console.log("Processing func -> SignUp");

    User.create({
        name: req.body.name,
        number_phone: req.body.number_phone,
        password: bcrypt.hashSync(req.body.password, 8)
    }).then(user => {
        Role.findAll({
            where: {
                name: {
                    [Op.or]: req.body.roles
                }
            }
        }).then(roles => {
            user.setRoles(roles).then(() => {
                res.send("User registered successfully!");
            });
        }).catch(err => {
            res.status(500).send("Error -> " + err);
        });
    }).catch(err => {
        res.status(500).send("Fail! Error -> " + err);
    })
}

exports.signin = (req, res) => {
    console.log("Sign-In");

    User.findOne({
        where: {
            number_phone: req.body.number_phone
        }
    }).then(user => {
        if (!user) {
            return res.status(404).send('User Not Found.');
        }

        var passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
        if (!passwordIsValid) {
            return res.status(401).send({ auth: false, accessToken: null, reason: "Invalid Password!" });
        }

        var token = jwt.sign({ id: user.id }, config.secret, {
            expiresIn: 86400 // expires in 24 hours
        });

        res.status(200).send({ auth: true, accessToken: token });

    }).catch(err => {
        res.status(500).send('Error -> ' + err);
    });
}

exports.userContent = (req, res) => {
    User.findOne({
        where: { id: req.userId },
        attributes: ['name', 'number_phone'],
        include: [{
            model: Role,
            attributes: ['id', 'name'],
            through: {
                attributes: ['userId', 'roleId'],
            }
        }]
    }).then(user => {
        res.status(200).json({
            "description": "User Content Page",
            "user": user
        });
    }).catch(err => {
        res.status(500).json({
            "description": "Can not access User Page",
            "error": err
        });
    })
}

exports.adminBoard = (req, res) => {
    User.findOne({
        where: { id: req.userId },
        attributes: ['name', 'number_phone'],
        include: [{
            model: Role,
            attributes: ['id', 'name'],
            through: {
                attributes: ['userId', 'roleId'],
            }
        }]
    }).then(user => {
        res.status(200).json({
            "description": "Admin Board",
            "user": user
        });
    }).catch(err => {
        res.status(500).json({
            "description": "Can not access Admin Board",
            "error": err
        });
    })
}

exports.managementBoard = (req, res) => {
    User.findOne({
        where: { id: req.userId },
        attributes: ['name', 'number_phone'],
        include: [{
            model: Role,
            attributes: ['id', 'name'],
            through: {
                attributes: ['userId', 'roleId'],
            }
        }]
    }).then(user => {
        res.status(200).json({
            "description": "Management Board",
            "user": user
        });
    }).catch(err => {
        res.status(500).json({
            "description": "Can not access Management Board",
            "error": err
        });
    })
}


我只在 Postman 里试过。
发布:http://localhost:4242/auth/signup

未处理的拒绝错误:WHERE参数“number_phone”具有无效的“undefined”值

谢谢你,谢谢

svgewumm

svgewumm1#

Sequelize 5.0开始,在where子句中不能有undefined键:
Sequelize将抛出where选项中所有未定义的键,在过去的版本中,undefined被转换为null。
请确保在请求的主体中传递number_phone,或者将|| null添加到where子句中以默认为null。

s5a0g9ez

s5a0g9ez2#

如果您在Postman上提出了请求,并且一切正常,则可能需要检查前端客户端
有时我们需要声明申请类型种类**,以使请求成功
只是为了检查,检查您的CORS配置,以便能够执行您想要执行的任何请求

这里有一些Express和CORS的文档

https://expressjs.com/en/resources/middleware/cors.html

这里是AXIOS文档,用于您在前端的请求

https://axios-http.com/docs/post_example

相关问题