【问题标题】:How to handle returned different http status codes separately in Fetch Api?如何在 Fetch Api 中分别处理返回的不同 http 状态码?
【发布时间】: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


【解决方案1】:

你可以实现如下,

export enum STATUSCODE{

     NOTFOUND= 401,
     ERROR = 500,
     ...
}
    
async loginUser() {
      let response = await this._service.loginUser(this.user)
      .then(response => {return response.json()})
      .then(response => {
     
        ...
        ...

        switch (response.status)) {
           case STATUSCODE.NOTFOUND: // do something here
                     break;
           case STATUSCODE.ERROR: // do something here
                     break;
        }
        
        ...
        ...
      })
      .catch(error => {alert("Something went wrong")});
}

旁注:您可以使用 HTTP Interceptor

在中心位置处理所有 http 状态代码

【讨论】:

  • statusCode 不是response 的有效属性。你的意思可能是status
  • switch语句中,response不再指HTTP Response,而是指解析后的JSON体。
【解决方案2】:

response 对象有一个属性status,这是服务器返回的http状态码。

【讨论】:

  • 问题是,无论错误代码是什么,如果响应不是 200,fetch api 都会 catch() 阻塞。我无法从“错误”变量中获得状态
  • @ChrisGarsonn 这不正确。来自 mdn 页面The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
【解决方案3】:

您可以在响应属性中看到 HTTP 状态。

status – HTTP status code, e.g. 200.
ok – boolean, true if the HTTP status code is 200-299.

知道您可以在 if 语句中访问 response.status 并进行比较。

【讨论】:

  • 问题是,无论错误代码是什么,如果响应不是 200,则 fetch api 将 catch() 块。我无法从“错误”变量中获得状态
  • 啊,是的,我可以看到。也许您可以在 catch() 回调函数中访问错误变量并在那里执行您的逻辑。不知道这是否是正确的方法......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 2020-04-30
  • 2017-03-07
  • 2012-11-11
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
相关资源
最近更新 更多