【发布时间】: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