javascript - 未处理的拒绝错误 : WHERE parameter “number_phone” has invalid “undefined” value

标签 javascript mysql node.js express sequelize.js

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

模型/user.model.js

Code in backend


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

  return User;
}

路由器/verifySignUp.js

Code in backend



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

Code in backend


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 那里尝试过。

POST : http://localhost:4242/auth/signup



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

谢谢 !

最佳答案

Sequelize 5.0 开始,您的 undefined 子句中不能有 where 键:

Sequelize will throw for all undefined keys in where options, In past versions undefined was converted to null.


确保在请求正文中传递 number_phone 或将 || null 添加到 where 子句以默认为 null。

关于javascript - 未处理的拒绝错误 : WHERE parameter “number_phone” has invalid “undefined” value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58059869/

相关文章:

node.js - 找不到模块 'socket.io/node_modules/redis'

angularjs - 在 Node 应用程序中使用 Angular $http 服务

javascript - Vega Charts 抛出类型定义错误

javascript - 如何对多个对象使用一个处理程序?

javascript - 使用 Jest 和 enzyme 进行 IndexedDB 测试 - ReferenceError : indexedDB is not defined

javascript - 仅在将鼠标移至输入上方后才渲染文本文本标签

php - 使用 SQL 拉取去年最后一个月的数据

Javascript:通过 Google 标签管理器将 Mouseflow session ID 作为自定义维度推送到 Google Analytics

sql - 如何在 SQL 表中存储一组值

python - 更新未在 mysql 服务器上提交flask-sqlalchemy