【问题标题】:Accessing response body in Angular when HTTP Post fails with error 403当 HTTP Post 失败并出现错误 403 时在 Angular 中访问响应正文
【发布时间】:2022-01-26 17:30:28
【问题描述】:

我有一个 Angular 9 项目,我在其中使用 HttpClient 通过 HTTP 帖子执行登录。 如果登录失败,则返回 HTTP 403 和 JSON 响应,其中包含要在 UI 上显示的错误消息。

我的问题是我的错误处理程序总是用一个简单的字符串Forbidden 调用,而不是我想要的响应正文。我怎样才能检索响应正文?它已正确返回到浏览器。

我有这样的事情:

import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' }) 
export class AccountService {

    constructor(
        private http: HttpClient,
        // ...
    )


    login(userName, userPassword) {
        return this.http.post(`login`, {user: userName, password: userPassword}); 
    }
}

我有一个组件,它只是检索返回的错误并将其显示在 UI 上。

this.accountService.login(this.f.username.value, this.f.password.value)
    .subscribe(
        data => {
            this.router.navigate([this.returnUrl]);
        },
        error => {
            // error is a string here
            this.alertService.error(error.errorMessage); 
            this.loading = false;
        });

【问题讨论】:

    标签: angular typescript post


    【解决方案1】:

    如果您想从响应中显示一些错误消息,您可以通过创建错误拦截器来实现。

    Check this and this

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 2018-04-01
      • 2020-06-11
      • 1970-01-01
      • 2015-03-11
      • 2013-12-21
      • 1970-01-01
      相关资源
      最近更新 更多