javascript - 从 Angular 8 中的 http 响应读取错误状态代码时为 "Cannot read property message of null"

标签 javascript angular typescript asp.net-core angular8

我正在使用 Angular 8 进行开发,并向 .net 核心 Web API 发出 http post 请求,如果用户名或密码不正确,则返回 400 状态代码。 Chrome 控制台显示返回了 400,但是当从 http 请求响应中提取返回的可观察对象中的状态代码时,我收到了 Cannot read property message of null 错误消息。我怎样才能解决这个问题?谢谢。

登录组件:

this.authService.login(
      {
        username: this.f.username.value,
        password: this.f.password.value
      }
    )
    .subscribe(
        res => {
          if(this.returnUrl != null){
            this.router.navigate([this.returnUrl]);
          }
          else {
            let role = res.role[0];
            this.router.navigate([`${role}`]);
          }

        },
        error => {
            //This line throws the error. the value of error is "cannot read message property of null" and error.status = undefined.
            alert(error.status);
            this.badCredentials = true;
            this.router.navigate(['/login']);
        });

授权服务:

login(user: {username: string, password: string}) :Observable<any>{
    return this.http.post<any>(`${applicationPaths.loginApiUrl}`, user)
    .pipe(
      tap(response => this.doLoginUser(response)),
      catchError((error): any => {

              return throwError(`Connection Error: ${error}`);
          }
      ));
  }

更新:

我在我的 Angular 应用程序中将我的代码更新为以下内容,它仍然返回相同的错误消息:服务器返回代码:未定义,错误消息是:无法读取 null 的属性“消息”

login(user: {username: string, password: string}) :Observable<any>{
    return this.http.post<any>(`${applicationPaths.loginApiUrl}`, user)
    .pipe(
      tap(response => this.doLoginUser(response)),
      catchError(this.handleError));
  }

  handleError(err: HttpErrorResponse) {
    let errorMessage = '';
    if(err.error instanceof ErrorEvent){

      //a client-side or network error occured. Handle it accordingly.
      errorMessage = `An error occured: ${err.error.message}`;

    } else {
      //The back-end returned an unsuccessful response code.
      errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
    }

    console.error(errorMessage);
    return throwError(errorMessage);
  }

但是当我执行 return BadRequest("incorrect username or password.");return BadRequest(); 时,它会返回错误消息 Server returned code : undefined,错误信息为:undefined。所以这可能与我在后端从 web api 返回错误代码的方式有关。我不确定那里需要修复什么。

最佳答案

仅当您observe: 'response'

时才会提供状态

尝试像这样编辑您的 authService

login(user: {username: string, password: string}) :Observable<any>{
    return this.http.post<any>(`${applicationPaths.loginApiUrl}`, user
      // NEW CODE HERE
      { observe: 'response' }
    )
    .pipe(
      tap(response => this.doLoginUser(response)),
      catchError((error): any => {

              return throwError(`Connection Error: ${error}`);
          }
      ));
  }

关于javascript - 从 Angular 8 中的 http 响应读取错误状态代码时为 "Cannot read property message of null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57851496/

相关文章:

javascript - 如何使用 jhipster 和 Angular 在选项中显示图片?

css - 使用 Sass 的 Angular 6 元素

angular - ./node_modules/bootstrap/dist/css/bootstrap.css 中的错误

typescript - 在 typescript 中,类型 `object` 和 `Record<any, any>` 之间有区别吗?

javascript - Angular 2 - ngShow 等效?

javascript - 我可以在多选中的选项上绑定(bind)什么事件?

javascript - 在 Spring Boot 和 Angular 之间处理 CORS 和 CSRF

javascript - 学生的分数相加为一名学生的总分

javascript - 在纯 ReactJS(功能)组件中渲染子 Prop

javascript - 如何通过 Typescript 中的迭代处理数组字符串