【发布时间】:2020-07-29 17:41:35
【问题描述】:
我正在向后端发送请求,但后端可以返回不同的状态码,如下所示:
public ResponseEntity<UserDto> loginUser(@RequestBody UserDto userDto) {
User userObj;
if (isNull(userDto.getEmail()) || isNull(userDto.getPassword())) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
else {
try {
userObj = userService.getUserByEmailAndPassword(userDto);
if (isNull(userObj)) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return ResponseEntity.ok(modelMapper.map(userObj, UserDto.class));
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
而我之前的 fetch 方法调用版本是:
async loginUser() {
let response = await this._service.loginUser(this.user)
.then(response => {return response.json()})
.then(response => {
if (response.error) {
this.dialog.open(ErrorDialogComponent);
} else {
this._router.navigate(['/mainpage'], {queryParams: {userId: response.userId}})
}
})
.catch(error => {alert("Something went wrong")});
}
我想要做什么,根据响应的状态代码处理不同的响应,例如:
async loginUser() {
let response = await this._service.loginUser(this.user)
.then(response => {return response.json()}).
then if status code is 401 (do this)
then if status code is 500 (do this)
.
.
etc
我该如何处理?
【问题讨论】:
-
处理响应代码的逻辑可能需要在第一个
then()中完成。状态码应该存在于response参数的某个位置 -
您是否从 API 获取状态码?
-
尽管您可能需要仔细检查。由于端点返回状态码为 401 和 500,这些不是成功状态码,因此可能正在执行失败回调。这将是对第一个
then()的二次回调 -
@micronyks 是的,我正在从后端 api 获取状态代码
标签: javascript angular fetch httprequest fetch-api