簡體   English   中英

如何在Fetch Api中分別處理返回不同的http狀態碼?

[英]How to handle returned different http status codes separately in Fetch Api?

我正在向后端發送請求,但后端可以返回不同的狀態代碼,如下所示:

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

我該如何處理?

您可以執行以下操作,

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攔截器在中心位置處理所有 http 狀態代碼

response object 有一個屬性狀態,它是服務器返回的 http 狀態代碼。

您可以在響應屬性中查看 HTTP 狀態。

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

知道您可以在 if 語句中訪問 response.status 並進行比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM