"Failed to load resource: the server responded with a status of 400 ()" error on Angular code...

Discussão em 'Angular' iniciado por ADITYA CHAKRABORTY, Dezembro 9, 2024.

  1. I am currently building this angular app, but for some reason the fetch posts for login and signup give me this error. First time when I ran the app, it went smoothly, after I loaded it a second time it started showing this error

    auth.component.ts: (login page typescript)

    import { NgForm } from '@angular/forms';
    import { Router } from '@angular/router';
    import { Observable } from 'rxjs';
    import {
    AuthResponseData,
    AuthService,
    } from '../../services/auth/auth.service';

    @Component({
    selector: 'app-auth',
    templateUrl: './auth.component.html',
    })
    export class AuthComponent {
    isLoginMode = true;
    isLoading = false;
    error: string = null;

    constructor(private authService: AuthService, private router: Router) {}

    onSwitchMode() {
    this.isLoginMode = !this.isLoginMode;
    }

    onSubmit(form: NgForm) {
    if (!form.valid) {
    return;
    }
    const email = form.value.email;
    const password = form.value.password;

    let authObs: Observable<AuthResponseData>;

    this.isLoading = true;

    if (this.isLoginMode) {
    authObs = this.authService.login(email, password);
    } else {
    authObs = this.authService.signup(email, password);
    }

    authObs.subscribe(
    (resData) => {
    console.log(resData);
    this.isLoading = false;
    this.router.navigate(['/recipes']);
    },
    (errorMessage) => {
    console.log(errorMessage);
    this.error = errorMessage;
    this.isLoading = false;
    }
    );

    form.reset();
    }
    }


    And my auth.service.ts:

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpErrorResponse } from '@angular/common/http';
    import { Router } from '@angular/router';
    import { catchError, tap } from 'rxjs/operators';
    import { throwError, BehaviorSubject } from 'rxjs';

    import { User } from '../../models/user.model';

    export interface AuthResponseData {
    kind: string;
    idToken: string;
    email: string;
    refreshToken: string;
    expiresIn: string;
    localId: string;
    registered?: boolean;
    }

    @Injectable({ providedIn: 'root' })
    export class AuthService {
    user = new BehaviorSubject<User>(null);
    private tokenExpirationTimer: any;

    constructor(private http: HttpClient, private router: Router) {}

    signup(email: string, password: string) {
    return this.http
    .post<AuthResponseData>(
    'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=****',
    {
    email: email,
    password: password,
    returnSecureToken: true,
    }
    )
    .pipe(
    catchError(this.handleError),
    tap((resData) => {
    this.handleAuthentication(
    resData.email,
    resData.localId,
    resData.idToken,
    +resData.expiresIn
    );
    })
    );
    }

    login(email: string, password: string) {
    return this.http
    .post<AuthResponseData>(
    'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=****',
    {
    email: email,
    password: password,
    returnSecureToken: true,
    }
    )
    .pipe(
    catchError(this.handleError),
    tap((resData) => {
    this.handleAuthentication(
    resData.email,
    resData.localId,
    resData.idToken,
    +resData.expiresIn
    );
    })
    );
    }

    autoLogin() {
    const userData: {
    email: string;
    id: string;
    _token: string;
    _tokenExpirationDate: string;
    } = JSON.parse(localStorage.getItem('userData'));
    if (!userData) {
    return;
    }

    const loadedUser = new User(
    userData.email,
    userData.id,
    userData._token,
    new Date(userData._tokenExpirationDate)
    );

    if (loadedUser.token) {
    this.user.next(loadedUser);
    const expirationDuration =
    new Date(userData._tokenExpirationDate).getTime() -
    new Date().getTime();
    this.autoLogout(expirationDuration);
    }
    }

    logout() {
    this.user.next(null);
    this.router.navigate(['/auth']);
    localStorage.removeItem('userData');
    if (this.tokenExpirationTimer) {
    clearTimeout(this.tokenExpirationTimer);
    }
    this.tokenExpirationTimer = null;
    }

    autoLogout(expirationDuration: number) {
    this.tokenExpirationTimer = setTimeout(() => {
    this.logout();
    }, expirationDuration);
    }

    private handleAuthentication(
    email: string,
    userId: string,
    token: string,
    expiresIn: number
    ) {
    const expirationDate = new Date(new Date().getTime() + expiresIn * 1000);
    const user = new User(email, userId, token, expirationDate);
    this.user.next(user);
    this.autoLogout(expiresIn * 1000);
    localStorage.setItem('userData', JSON.stringify(user));
    }

    private handleError(errorRes: HttpErrorResponse) {
    let errorMessage = 'An unknown error occurred!';
    if (!errorRes.error || !errorRes.error.error) {
    return throwError(errorMessage);
    }
    switch (errorRes.error.error.message) {
    case 'EMAIL_EXISTS':
    errorMessage = 'This email exists already';
    break;
    case 'EMAIL_NOT_FOUND':
    errorMessage = 'This email does not exist.';
    break;
    case 'INVALID_PASSWORD':
    errorMessage = 'This password is not correct.';
    break;
    }
    return throwError(errorMessage);
    }
    }


    I have double checked API key, I have checked the authorized domains on firebase. None of it works

    Continue reading...

Compartilhe esta Página