How do I catch a backend error and not log into the application?

Asked

Viewed 155 times

1

Guys, good night, I researched several topics and tried several solutions and unfortunately I could not adjust the error. I am developing an application with Angular and my Python backend, at the moment I am doing login authentication (no token for now), when sending an HTTP request with username and password to my server it checks if there is registration in the bank and if there should redirect to the route '/Dashboard', but regardless of the username exists in the bank it redirects. Below are lines of code:

My Component:

  userLogin(){
// Pegando os valores do HTML INPUT e jogando nas constantes
    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.authService
        .authenticate(username, password)
    .subscribe(
      () => this.router.navigate(['dashboard']),
            err => {
        console.log(this.loginForm.value)
                console.log(err);
        this.loginForm.reset();
        alert('Erro')
            }
        )
    }

My Service:

  constructor(private http: HttpClient) { }

    authenticate(username: string, password: string) {    
      return this.http.post(API_URL, {"username":username, "password":password})
  }

My backend in python:

class Login(Resource):
    def post(self):
        parser.add_argument('username', type=str)
        parser.add_argument('password', type=str)
        args = parser.parse_args()
        print(args)
        password = hashlib.md5(args['password'].encode('utf-8')).hexdigest()
        sql = "SELECT * FROM usuarios WHERE username = (%s) and password = (%s)"
        value = (args['username'], password)
        dbcursor.execute(sql, value)
        result = dbcursor.fetchall()
        print(result)
        if len(result) > 0:
            return {"message": "user valido"}
        else:
            return {"message": "user invalido"}

In my browser I get the Return if the user is valid or not and even so, whether or not my user is redirected to the Dashboard route

  • 1

    Hello! So that you can have help from colleagues, I suggest you exchange your code images for your pure code. The Code makes it easy for anyone to help you. Do not use image. Place your code here, editing your question and added to the content. Greetings.

  • Hello Fabiano, thanks for the tip, providing for now!

3 answers

2

Try trading your subscribe for this one:

.subscribe((res) => {
  if(res.message == 'user valido'){
      this.router.navigate(['dashboard'])
  }}
  ,(err: HttpErrorResponse) => {

      alert('erro');
}
  • Hello Veronese, it does not work that way, had tried, but it does not find the "res.message", because it does not find the message property*

  • when you are on the console.log(res), what is returned? perhaps depending on the return structure can be: res.body.message

  • this is my res: {message: "user invalido"} message: "user invalido" proto: Object

  • Veronese, I answered my question with what worked based on your idea

  • @Fernando glad it all worked out.

  • thanks for the light and I couldn’t help noticing the image of the magebot (good times), know tell me if this form of authentication I did is correct? validating by the message sent from my backend?

  • is not wrong, but sooner or later you will need to return a token from your backend and save in the frontend’s localStorage and then every request you make has to send this token, through this token you take the data of the user who requested that api. You will also need to save the token to create a route guardian, whenever you have a token on localStorage do not let go to login screen etc...

Show 2 more comments

1

Guys, I got it this way, but I don’t know if it’s the right way:

 this.authService
    .authenticate(username, password)
.subscribe((res) => {
  if(res ["message"] == 'user valido') {
    this.router.navigate(['dashboard'])
  }
  else {
    console.log('user invalido')

}

0

The best would be your backend return 501 which is the default for unauthorized and you handle the catch error as you had done.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.