我正在使用 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/