Node.js Http POST永远挂起mysql查询

时间:2017-08-05 22:41:30

标签: mysql node.js express post coffeescript

这里我要做的是检查db中是否有用户名和电子邮件匹配,如果没有,请注册新用户。使用coffescript。

当我尝试对路线进行POST时,摩根打印

  

POST / register - - ms - -

邮递员永远挂起......

没有控制台错误,也没有POSTMAN响应......

任何人都知道造成这个问题的原因是什么?

app.post '/register', (req, res, next) ->
  email = req.body.email
  username = req.body.username
  emailORUsernameExists = checkEmailUsername email, username

  unless emailORUsernameExists
    password = req.body.password
    query = "INSERT INTO users (email, username, password) VALUES (" + email + "," + username + "," + password + ")"
    bcrypt.genSalt 10, (err, salt) ->
      bcrypt.hash password, salt, (err, hash) ->
        # Store hashed password in DB.
        connection.query query, (err, result) ->
          if err
            throw err
          console.log "1 record inserted!"

checkEmailUsername = (mail, user) ->
  query = "SELECT * FROM users WHERE email = ? OR username = ?"
  connection.query query, [mail, user], (err, row, fields) ->
    if err
      console.log err

    if row.length > 0
      # return true if there is a matching username and password
      return true
    else
      # if there is not, return false
      return false

另外,JS版

  app.post('/register', function(req, res, next) {
    var email, emailORUsernameExists, password, query, username;
    email = req.body.email;
    username = req.body.username;
    emailORUsernameExists = checkEmailUsername(email, username);
    if (!emailORUsernameExists) {
      password = req.body.password;
      query = "INSERT INTO users (email, username, password) VALUES (" + email + "," + username + "," + password + ")";
      return bcrypt.genSalt(10, function(err, salt) {
        return bcrypt.hash(password, salt, function(err, hash) {
          return connection.query(query, function(err, result) {
            if (err) {
              throw err;
            }
            return console.log("1 record inserted!");
          });
        });
      });
    }
  });

  checkEmailUsername = function(mail, user) {
    var query;
    query = "SELECT * FROM users WHERE email = ? OR username = ?";
    return connection.query(query, [mail, user], function(err, row, fields) {
      if (err) {
        console.log(err);
      }
      if (row.length > 0) {
        return true;
      } else {
        return false;
      }
    });
  };

1 个答案:

答案 0 :(得分:0)

res永远不会在代码中的任何地方调用,导致请求挂起。

对代码采用更现代的方法如下所示:

app.post('/register', async (req, res, next) => {
  const { email, username } = req.body

  // Since our function now returns a Promise we can use await.
  // Avoids that triangle of doom/callback hell.
  const emailORUsernameExists = await checkEmailUsername(email, username)

  if (!emailORUsernameExists) {
    let { password } = req.body

    // Hash the password BEFORE saving to the database
    const salt = await bcrypt.genSalt(10)
    password = await bcrypt.hash(password, salt)

    const query = `INSERT INTO users (email, username, password) VALUES (${email}, ${username}, ${password}`

    connection.query(query, (err, result) => {
      if (err) {
        // Something went wrong, let the client know this.
        res.status(500).json({ error: err })
        return
      }
      // All went well.
      res.status(201).json()
    })
  }
})

function checkEmailUsername (mail, user) {
  const query = 'SELECT * FROM users WHERE email = ? OR username = ?'

  // I don't think node-mysql supports Promises.
  // Promise is used to make the code read more synchronous
  return new Promise((resolve, reject) => {
    connection.query(query, [mail, user], (err, row, fields) => {
      if (err) {
        reject(err)
      }
      if (row.length > 0) {
        resolve(true)
      } else {
        resolve(false)
      }
    })
  })
}

上面的代码未经测试,因此您需要根据自己的需要进行调整。