服务器出错时如何获取响应内容
How to get the response content when server error
我希望我能在服务器returns错误代码5XX或4XX时得到响应内容。
这是我的配置:
API 休息 (Laravel) :
public function login(Request $request) {
$this->validateLogin($request);
if ($this->attemptLogin($request)) {
$user = $this->guard()->user();
$user->generateToken();
return response()->json($user, 200);
}
return response()->json('Login or password unknown', 401);
}
Angular 服务:
public getUser(user: User): Observable<any> {
return this.httpClient.post(this.employeeAPI +
'login', JSON.stringify(user), { headers: this.headers });
}
Angular 分量:
public login(): void {
this.loginService.getUser(this.user).subscribe(
(user) => {
this.user = user;
this.router.navigate(['/home']);
},
(error) => {
// Is it possible to get the content of response ?
}
);
}
谢谢。
要想用更高的角度看回复,就得这样观察回复:
return this.httpClient.post(this.employeeAPI
+ 'login', JSON.stringify(user), { headers: this.headers, observe: 'response' });
响应的类型为 HttpResponse
。这意味着您自己从响应中提取 body
,但这也允许您检索状态代码。
我希望我能在服务器returns错误代码5XX或4XX时得到响应内容。
这是我的配置:
API 休息 (Laravel) :
public function login(Request $request) {
$this->validateLogin($request);
if ($this->attemptLogin($request)) {
$user = $this->guard()->user();
$user->generateToken();
return response()->json($user, 200);
}
return response()->json('Login or password unknown', 401);
}
Angular 服务:
public getUser(user: User): Observable<any> {
return this.httpClient.post(this.employeeAPI +
'login', JSON.stringify(user), { headers: this.headers });
}
Angular 分量:
public login(): void {
this.loginService.getUser(this.user).subscribe(
(user) => {
this.user = user;
this.router.navigate(['/home']);
},
(error) => {
// Is it possible to get the content of response ?
}
);
}
谢谢。
要想用更高的角度看回复,就得这样观察回复:
return this.httpClient.post(this.employeeAPI
+ 'login', JSON.stringify(user), { headers: this.headers, observe: 'response' });
响应的类型为 HttpResponse
。这意味着您自己从响应中提取 body
,但这也允许您检索状态代码。