简体   繁体   中英

Handle duplicates with express.js

So I am trying to create a login for the first time with express and react using Postgres. My user can be added to the database so I jumped into handling duplicates. I am using the findUserByEmail function to find my email and then, in my routes, calling that function before posting the email. I hope you guys can help me, I've been 1 week with this.

This is my queries.js where I :

const findUserByEmail = email => {
  return pool.query("SELECT * FROM users WHERE email = $1", [email]);
};

const createUser = (request, response) => {
  const date_created = new Date();
  const { username, email, password } = request.body;

  bcrypt.genSalt(saltRounds, function(err, salt) {
    bcrypt.hash(password, salt, function(err, hash) {
      pool.query(
        `INSERT INTO users (username, email, password, date_created) VALUES ($1, $2, $3, $4 )`,
        [username, email, hash, date_created],
        (error, results) => {
          // console.log("---------->", email);
          if (error) {
            throw error;
          }
          response.status(201).send(`User added with ID: ${results.insertId}`);
        }
      );
    });
  });
};



and this is my index.js:

// ...Other connection code

//Routes

app.get("/users", queries.getUsers);
app.get("/user/:id", queries.getUserById);

app.post("/signup/user", (req, res, next) => {
  console.log(req.body.email, "----------1");
  queries
    .findUserByEmail(req.body.email)
    .then(user => {
      console.log(user.rows.length);
      if (user.rows.length < 0) {
        res.status(400).send("this email is already in use");
      } else {
        console.log("Hello");
        queries.createUser;
      }
    })
    .catch(err => {
      console.log(err);
      res.status(500).send("Something went wrong");
    });
});

app.put("/user/:id", queries.updateUser);
app.delete("/user/:id", queries.deleteUser);

app.listen(port, () => {
  console.log(`App running on port ${port}.`);
});

Is not giving me an error, but when I submit a new user, keeps posting forever and does not change.

My post request worked till now without using the findUserByEmail.

Thanks for your help.

You have no guarantee that findUsersByEmail will find anything, even if there is a previous call, creating a user. The reason is that the query creating the user may not have returned yet.

You need database constraints to deal with this.

Put a unique constraint on the email field and handle duplicate exceptions correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM