'Node.js server gets stuck after a few API calls

I have a node.js application where I'm using the sign in functionality. I'm facing an issue; that is, when I try to sign in, sometimes the request gets stuck. It won't return anything until I refresh the node.js server. Can anybody take a look at the code and help me out what am I doing wrong here?

Here is my Controller function

 export const authenticate = async (
  req: Request,
  res: Response
): Promise<void> => {
  try {
    console.log("Login")
    const result: DataObject = await model.authenticate(
      req.body.username,
      req.body.password
    )
    const { status, data } = result

    res.status(status)
    if(status==200) {
      console.log(status)
      const u : User = data as User;
      const token = jwt.sign({ id: u.id }, process.env.JWT_SECRET as string)
      
      res.json({token: token})
      
    }
    else {
      res.json(data)
    }
  } catch (error) {
    res.status(NOT_FOUND)
    res.json(error)
  }
}

And my Model method.

 async authenticate(username: string, password: string): Promise<DataObject> {
    try {
      
      const sql =
        "SELECT * FROM users WHERE username=$1"
      const conn: PoolClient = await Client.connect()

      const result: QueryResult<User> = await conn.query(sql, [username])
      const { rows } = result

      if (rows.length > 0) {
        
        const user: User = rows[0]
        const pepper: string = process.env.PASSWORD_HASH as string
        const pepperedPass = password + pepper;
        const validPass : boolean = bcrypt.compareSync(pepperedPass, user.password_digest);
       
        if (validPass) {
          const result: DataObject = {
            status: OK,
            data: user,
          }
          return result
        }
        else {
          const passErr: DataObject = {
            status: NOT_FOUND,
            data: "Incorrect Password",
          }
          return passErr
        }
      }
      
      const userErr: DataObject = {
        status: NOT_FOUND,
        data: "No User found with this Username",
      }
      return userErr

    } catch (error) {
      const userErr: DataObject = {
        status: NOT_FOUND,
        data: "No User found with this Username",
      }
      return userErr
      throw new Error(`Not found, ${error}`)
    }
  }

I have tried res._destroy, res.set("Connection", "close"); but the issue persists.

Any suggestion/solution is appreciated.

Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source