【问题标题】:"Cannot read property message of null" when reading error status code from http response in Angular 8从Angular 8中的http响应读取错误状态代码时“无法读取null的属性消息”
【发布时间】:2019-09-09 09:44:06
【问题描述】:

我正在使用 Angular 8 开发并向 .net 核心 Web api 发出 http post 请求,如果用户名或密码不正确,则返回 400 状态代码。 Chrome 控制台说 400 返回,但是当从 http 请求响应中提取返回的 observable 中的状态代码时,我收到 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 应用程序中将我的代码更新为以下内容,但它仍然返回相同的错误消息:Server returned code: undefined, error message is: Cannot read property 'message' of 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, error message is: undefined。所以也许这与我从后端的 web api 返回错误代码的方式有关。我不确定那里需要修复什么。

【问题讨论】:

  • 哪里有这个错误?向我们展示有错误的代码
  • @TonyNgo 我在上面发布的登录组件代码中的alert(error.status); 行收到错误消息。我对其进行了编辑以指示它发生的位置。该行抛出错误:cannot read message property of undefined 并且在使用 chrome 调试器时,它说 error.status 未定义。

标签: javascript angular typescript asp.net-core angular8


【解决方案1】:

仅当您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}`);
          }
      ));
  }

【讨论】:

  • 我将其更改为这个,但仍然收到该错误消息。 return this.http.post&lt;any&gt;(${applicationPaths.loginApiUrl}, user, { observe: 'response' })。语法正确吗?
  • 你试过控制台记录响应和错误吗?
  • 我把它改成了console.log(error.status),它在chrome控制台中显示“未定义”。
  • 我把它改成了console.log(error),上面写着:TypeError: Cannot read property 'message' of null
【解决方案2】:

像这样将{ observe: 'response' } 添加到您的代码中

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

然后尝试像这样在你的 catchError 中访问你的错误数据

error.statusText
error.statusCode

编辑你应该在你的控制器中使用这个代码

 return BadRequest();

你的代码

return StatusCode(400);

只返回状态码

【讨论】:

  • 我试过了,它在控制台中显示:Connection Error: undefined 如果我只是尝试输出error,它会显示:Connection Error: TypeError: Cannot read property 'message' of null
  • 你能说明如何从 .net 核心控制器返回数据吗?
  • 我这样返回它:return StatusCode(400); 但如果我这样返回它:return BadRequest("bad credentials"); 它会在控制台中显示Connection Error: Ok
  • 我把它改成了return BadRequest(),控制台仍然说:TypeError: Cannot read property 'message' of null
【解决方案3】:
  1. 在您的 .NET API 中:return BadRequest("Incorrect username or password");
  2. 在您的 Angular 应用程序中:
    catchError((error): any => {
                  return throwError(`Connection Error: ${error.error}`);
              }
          ));

【讨论】:

  • 我试过了,它仍然在控制台中给出以下错误:Connection Error: undefined
  • 如果您尝试return throwError(`Connection Error: ${error}`); 会怎样?这应该将错误对象返回到您的控制台。
  • 在我的项目中是这样的:this.http.get&lt;Data[]&gt;('apiUrl').subscribe(result =&gt; { this.chartData = result; }, error =&gt; { this.alertify.error(error.error); });
  • 登录API:public IActionResult Login([FromBody] User user) { if (user == null) { return BadRequest("Invalid client request"); } try { } catch (HttpRequestException) { return BadRequest("Cannot connect to the IoT server."); } catch (Exception) { return BadRequest("Cannot login."); }
【解决方案4】:

我和你有同样的问题。谷歌搜索把我带到了这里。

在我的情况下,我收到这个是因为我错误地将我的 API 方法注释为 HttpGet 而不是 HttpPost!

该消息似乎并没有真正反映这一点,但是当我修复它工作的 API 时。

【讨论】:

    【解决方案5】:

    查看您的 error.intercepter.ts 并将其更改为

    [ 常量错误 = err.error.message || err.statusText; ]

    运气

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2021-11-07
      相关资源
      最近更新 更多