正确的身份验证NodeJS Express MySQL

时间:2018-10-18 09:17:00

标签: mysql node.js express

所以我有这个查询,我对逻辑的工作方式感到困惑。 我正在创建一种新的用户注册方法,并且在其中有一种检查方法,以确定用户是否使用相同的电子邮件。 发布查询时,我正在使用POSTMAN。

第一个查询可以正常工作,既可以使用电子邮件检查方法,也可以注册新的查询;对于第二个查询,可以使用电子邮件检查方法,但是用新电子邮件注册均无效,POSTMAN会一直加载直到一分钟左右说“无法得到答复”。

第一个(作品)

exports.postContact = router.post("/api/users/new", (req, res) => {
  var today = new Date();
  var users = {
    "first_name": req.body.first_name,
    "last_name": req.body.last_name,
    "email": req.body.email,
    "password": req.body.password,
    "created": today,
    "modified": today
  }

  var email = req.body.email;

  mySQL.query('SELECT * FROM users WHERE email = ?', [email], function (err, results, fields) {
    if (results.length > 0) {
      if (results[0].email == email) {
        res.send({
          "code": 204,
          "status": 'Failed',
          "message": "This email address is already registered, please login instead"
        });
      }
    }
    else {
      mySQL.query("INSERT INTO users SET ?", users,
        (err, results, fields) => {
          if (err)
            res.send({
              "code": 400,
              "status": 'Failed',
              "message": 'Something wrong with the connection'
            })
          res.send({
            "code": 400,
            "status": 'Success',
            "message": 'User is successfully registered'
          })
        }
      );
    }
  });
});

第二个(不工作)

exports.postContact = router.post("/api/users/new", (req, res) => {
  var today = new Date();
  var users = {
    "first_name": req.body.first_name,
    "last_name": req.body.last_name,
    "email": req.body.email,
    "password": req.body.password,
    "created": today,
    "modified": today
  }

  var email = req.body.email;

  mySQL.query('SELECT * FROM users WHERE email = ?', [email], function (err, results, fields) {
    if (results.length > 0) {
      if (results[0].email == email) {
        res.send({
          "code": 204,
          "status": 'Failed',
          "message": "This email address is already registered, please login instead"
        });
      }
      else {
        mySQL.query("INSERT INTO users SET ?", users,
          (err, results, fields) => {
            if (err)
              res.send({
                "code": 400,
                "status": 'Failed',
                "message": 'Something wrong with the connection'
              })
            res.send({
              "code": 400,
              "status": 'Success',
              "message": 'User is successfully registered'
            })
          }
        );
      }
    }
  });
});

1 个答案:

答案 0 :(得分:0)

可能希望刷新您的SQL语句。
我相信这是正确的:

INSERT INTO users SET ?

针对MySQL的正确插入查询:

INSERT INTO table
  (column1, column2, ... )
VALUES
  (expression1, expression2, ... ),
  (expression1, expression2, ... )

Here's a link for reference.