skip to Main Content
exports.signup = async (req, res) => {
  const { username, password, name } = req.body;

  // TODO: Validate if username exists
  
  await knex("users").insert({ username, password, name });
  
  const user = await knex("users").where({ username }).first();

  // const users = await knex("users").where({username});
  
  
  // if (users === username) {
  //   res.status(401).json({
  //     error: {
  //       message: "Username already exists"
  //     }
  //   })
  // } else {
    const token = jwt.sign({ username, id: user.id }, secret);
    console.log(token);
    res.json({ ...user, token });
  // }
};

I can’t throw an error when I enter username which already exist in database mySQL. It keeps crashing the server and doesn;t reach else

It keeps crashing the server and doesn’t reach else.

exports.up = function (knex) {
  return knex.schema.createTable("users", (table) => {
    table.increments('id').primary();
    table.string("username").notNullable().unique();
    table.string("password").notNullable();
    table.string("name").notNullable();
  });
};

exports.down = function (knex) {
  return knex.schema.dropTable("users");
};

username is unique.

2

Answers


  1. You can try - catch and analize the error code to see if it represents a unique key constraint violation in mySQL:

    exports.signup = async (req, res) => {
      const { username, password, name } = req.body;
    
      try {
        await knex('users').insert({ username, password, name });
    
        const user = await knex('users').where({ username }).first();
    
        const token = jwt.sign({ username, id: user.id }, secret);
        console.log(token);
        res.json({ ...user, token });
      } catch (err) {
        if (err.code === 'ER_DUP_ENTRY' || err.errno === 1062) {
          // User already exists...
        } else {
          // Server error...
        }
      }
    };
    
    Login or Signup to reply.
  2. Create unique constraint on username field in database.

    ALTER TABLE users ADD UNIQUE (username);

    And try again with same username it will throw error of duplicate entry.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search