Angular 16从Django捕获错误响应

bvjxkvbb  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(174)

我正在学习Angular,我在Angular 16.2.0中有一个标准的登录服务,后端是Django。我发布的登录信息都很好,但是当我捕获错误时,我只得到一般性的错误,Django正在发送个性化的错误消息,我试图捕获这些错误,以便能够在前端显示它们。
这是我的登录服务功能:

login(username: string, password: string): Observable<any> {
        return this.http.post(apiRoot + 'dj-rest-auth/login/',
            { username, password, },
        ).pipe(catchError((error: HttpErrorResponse) => {
            let errorMsg = '';
            if (error instanceof ErrorEvent) {

                errorMsg = `Error: ${error}`;
            } else {

                errorMsg = `Error Code: ${error},  Message: ${error.message}`;
                console.log(error.message)
            }

            return throwError(() => new Error(errorMsg));
        }));
    }

现在,如果出现错误,这就是我得到的全部:https://link.stars-nexus.com/dj-rest-auth/login/的HTTP失败响应:400好的。
在网络中,我有:Network Headers
Django正在发送个性化的错误消息作为响应:
Response Image
我试图抓住他们的信息,以便能够在前端向他们展示信件。Django负责所有的验证,并为每个错误提供适当的个性化反馈。有什么办法能抓住他们吗?谢谢你的问候。
能够从错误响应中捕获这些消息,并在前端显示它们。

sz81bmfz

sz81bmfz1#

我没有找到一个解决方案与Angular http客户端,所以我使用的请求,我需要很好的反馈消息从Django:axios-observable从:Axios Observables Doc
例如:登录服务:

import { Injectable, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';

import Axios from 'axios-observable';

import { Injectable, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';

import Axios from 'axios-observable';

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    import { Injectable, OnInit } from '@angular/core';
    import { Observable } from 'rxjs';
    import { environment } from 'src/environments/environment';

    import Axios from 'axios-observable';


    const apiRoot = environment.apiUrl;
    @Injectable({
        providedIn: 'root'
    })
    export class LoginService implements OnInit {

        constructor() { }

        ngOnInit(): void {
        }

        // We will use Axios observable in the https requests that need a nice feedback for errors.
        // Documentation: https://www.npmjs.com/package/axios-observable

        login(username: string, email: string, password: string): Observable<any> {
            let loginData
            if (username) {
                loginData = { username, password }
            } else if (email) {
                loginData = { email, password }
            } else {
                loginData = { username, email, password }
            }
            return Axios.post(apiRoot + 'dj-rest-auth/login/', loginData, { withCredentials: true });
        }
    }

Login组件:

import { Component, OnInit } from '@angular/core';
    import { AuthService } from 'src/app/services/auth/auth.service';
    import { LoginService } from 'src/app/services/auth/login.service';

    @Component({
        selector: 'app-login',
        templateUrl: './login.component.html',
        styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {

        form: any = {
            username: null,
            email: null,
            password: null
        };

        errorMessage: any = null

        constructor(private authService: AuthService, private loginService: LoginService) { }

        ngOnInit(): void {
            console.log(this.authService.isLoggedIn)
        }

        onSubmit() {
            const { username, email, password } = this.form;

            this.loginService.login(username, email, password).subscribe({
                next: (v) => { this.authService.saveUser(v.data.user);  },
                // Local storage variable is not affecting security as Django will check if user is really logged in or not.
                // We use this only to save some requests to server so if this local storage is false we will not ask the
                // server to check the status of user.
                error: (err) => { this.errorMessage = err.response.data; localStorage.removeItem('isLogetIn') },
            })

        }
    }

在登录html中,你可以直接从服务器向用户打印漂亮的错误消息:

<div *ngIf="errorMessage">
                        {{errorMessage?.non_field_errors}}
                    </div>

non_field_errors将被替换为要打印的错误名称。在控制台/网络中检查哪些错误名称来自Django。
参见示例:Example error message displayed to user
我知道这不是一个永久的解决方案,但直到Angular将整理HTTP客户端从Django给予好的错误消息,这将做。亲切问候,Ionut Zapotototchi

相关问题